ISO/IEC 10646 Information Technology – Universal Multiple-Octet Coded Character Set (UCS) plus Amendment 1:2005, Amendment 2:2006, Amendment 3:2008, and Amendment 4:2008, plus additional amendments and corrigenda, or successor
ES 语言是一种面向对象的编程语言,其主要用于在宿主环境中执行计算和操作可计算的对象。本规范定义的 ES 语言并不打算成为计算性自完备的;事实也如此,本规范并没有提供任何外部数据的输入和计算结果的输出。相反,我们所期望的是,ES 程序的计算环境,不仅会提供本规范中所描述的对象和其他设施,而且还能提供用于某些特定环境下的对象(除非是为了说明这些对象是用来提供某些属性和方法以供 ES 程序访问或调用的,否则这些对象的描述和行为都会超出本规范的范围)。
起初,设计 ES 语言的目的是为了将其作为一种脚本语言来使用,但是现在,ES 语言已经成为了一门被广泛使用的通用编程语言。脚本语言也是一种编程语言,不过其主要用于操作、定制和自动化现有系统的设施。在这类系统(如浏览器)中,用户可以通过用户界面使用这些已经可用的设施,而脚本语言正是一种,将这些有用的设施暴露给程序控制的机制。通过这种方式,现有系统为对象和设施提供一种宿主环境,从而完善了脚本语言的能力。因此,脚本语言旨在供专业和非专业程序员使用。
最初,ES 语言被设计为一门 Web 脚本语言,目的是提供一种机制,使浏览器中网页的呈现更加生动,并能够执行服务端计算,以作为基于 Web 的客户端/服务器架构的一部分。现在,ES 语言可以用来为各种宿主环境提供核心的脚本功能。因此,本文档的目的是,为不依赖于任何特定宿主环境的核心语言,作出规范。
ES 语言的用法已经超越了简单的脚本语言,现在,ES 语言可以在很多不同的环境和规模下,用于各种编程任务。随着 ES 语言使用范围的不断扩大,它所提供的功能和设施也逐步地增强。现如今,ES 语言已经是一个功能齐全的通用编程语言了。
ES 语言的一些设施和其他编程语言的类似;特别是下列参考中所描述的 Java™、Self 和 Scheme:
ISO/IEC 9899:1996, Programming Languages – C.
Gosling, James, Bill Joy and Guy Steele. The Java™ Language Specification. Addison Wesley Publishing Co., 1996.
Ungar, David, and Smith, Randall B. Self: The Power of Simplicity. OOPSLA '87 Conference Proceedings, pp. 227-241, Orlando, FL, October 1987.
IEEE Standard for the Scheme Programming Language. IEEE Std 1178-1990.
4.1网页脚本
Web 浏览器为了客户端的计算而引入了一个 ES 宿主环境,例如,它提供的对象有:windows,menus,pop-ups,dialog boxes,text areas,anchors,frames,history,cookies 及输入 / 输出等等。而且,该宿主环境还提供了一种可以让脚本代码绑定诸如改变焦点、页面和图片的加载、卸载、错误和中止,选择,表单提交和鼠标交互等事件的方法。脚本代码出现在 HTML 中,但显示出来的页面则是一个由用户界面元素和已固定的且计算过的文本以及图片的结合体。脚本代码可以根据用户的交互而做出相应的反应,并不需要存在一个主程序。
Web 服务器为服务端的计算提供了一个不一样的宿主环境,包括的对象有:requests,clients,files 以及数据锁定和分享机制。通过浏览器端脚本及服务端脚本的配合使用,在为一个基于 Web 的应用提供可定制用户界面的同时,也将计算分布到客户端和服务端进行。
每一种支持 ES 语言的 Web 浏览器和服务器都将它们自身的宿主环境作为 ES 语言的补充,以使得 ES 语言的执行环境变得完整。
4.2ES 概述
下面是非正式的 ES 语言概述 -- 并未描述语言的所有部分。此概述并非标准的一部分。
ES 语言是基于对象的:基本的语言和宿主设施都由对象提供,并且 ES 程序是一组可通信的对象。在 ES 语言中,对象是 0 个或多个带有特性的属性集合,特性决定每一个属性如何被使用。例如,当一个属性的可写特性 Writable 被设置为 false 时,任何试图更改此属性的值的 ES 代码都会执行失败。属性是一个容器,它可以用来存放其他对象、原始值、函数。原始值是以下内置类型的成员之一:Undefined, Null, Boolean, Number, String 和 Symbol;对象是内置类型 Object 的成员;函数是可调用的对象。方法是通过属性与对象关联的函数。
ES 语言定义了一组内置对象,其完善了 ES 语言实体的定义。这些内置对象包括全局对象,用于 ES 语言运行时语义的基础对象(包括 Object、Function、Boolean、Symbol 和各种 Error 对象),表示和操作数值的对象(包括 Math、Number 和 Date),用于文本处理的对象(String 和 RegExp),索引值集合的对象(包括 Array 和 9 种不同类型数组的对象,它们所有的元素都具有一个特定数字的数据表示),键集合的对象(Map 和 Set),支持结构化数据的对象(JSON, ArrayBuffer, SharedArrayBuffer 和 DataView),支持抽象控制的对象(生成器函数和 Promise),反射对象( Proxy 和 Reflect)。
ES 语言还定义一套内置运算符。ES 运算符包括:一元运算符、乘法运算符、加法运算符、位移运算符、关系运算符、相等运算符、二进制位运算符、二进制逻辑运算符、赋值运算符、逗号运算符。
大型的 ES 程序可以通过模块化编程实现,模块允许一个程序被划分为由语句和声明组成的多段序列。每个模块都会明确标识它所使用的声明,这些声明需要由其他模块(决定其中哪些声明可以供其他模块使用)提供。
ES 语法有意设计成与 Java 语法类似。ES 语法是松散的,目的是使其能够作为一个易于使用的脚本语言。例如,一个变量不需要它的类型被声明,属性也不需要与类型关联,定义的函数也不需要声明在函数调用语句的前面。
4.2.1对象
尽管 ES 包含 class 定义的语法,但 ES 中的对象根本上不是基于类的,基于类的语言有 C++、Smalltalk 或 Java。相反,ES 中的对象可以通过多种方式创建,如通过对象的字面量表示法或通过构造器(创建对象,然后执行初始化对象的代码 -- 即,为对象的所有或部分属性分配初始值)。每个构造器都是一个函数,都有一个叫做 “prototype” 的属性(用于实现基于原型的继承和共享属性)。对象可以通过对构造器使用 new 表达式来创建。例如,new Date(2009,11) 会创建一个新的日期对象。调用一个未使用 new 关键字的构造器的结果,依赖于构造器本身。例如,调用 Date() 会产生一个代表当前日期和时间的字符串表示,而不是创建一个新的对象。
尽管 ES 对象内部本质上并不是基于类的,但基于一个拥有共同的构造器函数、原型对象和方法的模式,来定义一个类似 class 的抽象也是很容易的。ES 内置对象本身遵循了这样一个类似 class 的模式。一开始, ES 2015 就包含了对 class 的语法定义,允许程序员精确地定义一个和内置对象一样的,基于相同的类似 class 的抽象模式的对象。
4.2.2ES 的严格模式变体
ES 语言认识到可能存在部分用户,希望限制语言中的某些功能。他们这样做可能是为了安全考虑,规避那些他们认为容易出错的功能,从而获得更强的错误检查,亦或是出于其他原因。为了支持这种可能的情况,ES 定义了语言的严格变体。该语言的严格变体,排除了常规 ES 语言中的某些特定语法和语义特征,并且修改了某些功能的详细语义。该严格变体还指定了额外的一些,必须抛出错误异常报告的错误条件;但在该语言的非严格模式下,这些条件并不被指定为错误。
ES 的严格变体通常被称为该语言的严格模式。严格模式的选择和严格模式语法和语义的使用,明确地依赖于各自的 ES 源文本单元上的级别。由于严格模式的选择,依赖于语法源文本单元上的级别,所以,严格模式只会在这样的一个源文本单元内施加带有局部效果的限制。严格模式不会限制或修改 ES 语义的任何方面,因为 ES 的语义必须保证,在多个源文本单元间的操作的一致性。一个完整的 ES 程序,可以由严格模式和非严格模式的 ES 源文本单元组成。在这种情况下,严格模式仅适用于,定义在一个严格模式源文本单元中的实际可执行代码。
为了符合本规范,一个 ES 实现必须实现两套,完全不受限制的 ES 语言和严格变体的 ES 语言,作为这份规范的定义。此外,实现必须支持,由非严格模式和严格模式源代码单元组合而成一个单独的复合程序。
在一些案例中,为了避免歧义,句法会使用,其 token 序列不会构成一个有效 ES Script 或者 Module 的,通用生成式 。例如,该技巧被用于对象字面量和对象解构模式。在这种情况下,为了进一步限制可接受的 token 序列,会提供一种更严格的后补文法。典型地,如果 "P 没有覆盖 N"(这里的 P 是一个解析节点 - 通用生成式的一个实例,N 是一个来自后补文法的非终止符),那么早期错误规则将用来定义一个错误条件。在这里,使用 N 作为目标符,再次解析最初与 P 匹配的 token 序列(如果 N 携带语法参数,那么它们会被设置为,与最初解析 P 时所使用的值,相同的值)。如果 token 序列不能被解析为 N 的单个实例,且没有多余的 token 时,则会发生错误。随后,算法使用形如 “被 P 覆盖的 N” 的短语来访问解析结果。结果将始终是解析节点(N 的一个实例,对于给定的 P 是唯一的),因为任何解析失败都会被一个早期错误规则检测到。
5.1.5文法标记
在文法生成式和本规范中,每当文本直接引用词法、正则表达式文法、数值型字符串文法中的终止符时,都会用等宽的字体表示。这些将以书面形式出现在脚本中。所有以这种方式指定的终止符,都可以理解为适当的 Unicode 码点(在基本的 Latin 字符范围内),而不是其他 Unicode 范围的任何类似码点。
算法步骤可以为任何的值,声明一个别名,形如 “Let x be someValue”。这些别名与引用是类似的,因为 x 和 someValue 都指向相同的底层数据,且数据的修改对两者都是可见的。如果想要避免类似引用的行为,那么,算法步骤应该明确地创建一个 someValue 的副本:例如,“Let x be a copy of someValue” 可以创建一个 someValue 的浅拷贝。
一旦别名被声明,可以在任何后续步骤中引用它,但不得在该别名声明之前的步骤中引用它。可以使用 “Set x to someOtherValue” 的形式对别名进行修改。
5.2.1抽象操作
为了在本文档的多个部分方便抽象操作的使用,一些叫做抽象操作的算法,被命名和书写成带参数的函数形式,以便它们可以被其它包含该名字的算法复用。抽象操作可以以一个函数的应用形式(例如,OperationName(arg1, arg2))被引用。一些抽象操作可以被当做是,一种类似 class 的规范抽象的多形态分配方法。这样的类似 method 的抽象操作,可以以一种方法的应用形式(例如,someValue.OperationName(arg1, arg2))被引用。
5.2.2句法导向的操作
句法导向的操作是一种被命名的操作,它的定义由算法组成,每一个算法都和 ES 文法中的一个或多个生成式相关联。一个有多种替代子定义的生成式,都会存在一个严格区别的算法与之对应。当一个算法与一个文法生成式相关联,它或许会引用可选生成式的终止符或非终止符,就相当于它们是算法的参数一样。当以这样的一种方式使用时,非终止符会在解析源文本时,参考实际的可选定义来与之匹配。
Let status be the result of performing SyntaxDirectedOperation of SomeNonTerminal.
Let someParseNode be the parse of some source text.
Perform SyntaxDirectedOperation of someParseNode.
Perform SyntaxDirectedOperation of someParseNode passing "value" as the argument.
除非显式指定,否则所有的链式生成式,对每个操作都有一个隐式的定义,即每个操作都可能被应用到该生成式的左边 - 非终止符。隐式定义会简单地,把携带有相同参数的相同操作(如果有的话),重复应用到链式生成式的唯一的右边 - 非终止符,然后返回结果。例如,假设某些算法有一个形如:“Return the result of evaluating Block” 的步骤,如这个生成式:
属性可以使用键值来标识。一个属性的键值是一个 ES String 值 或 Symbol 值。所有的 String 和 Symbol 值,包括空字符串,都是有效的属性键。属性名是键值为 String 值的属性键。
整数索引是一个值为数值型字符串 (见 7.1.16) 的属性键,它的数值是 +0 或一个小于 253-1 的正整数。数组索引是一个整数索引,它的数值 i 在范围 +0 ≤ i < 232-1 内。
属性键可以用来访问属性和它的值。对于属性而言,存在两种访问类型:get 和 set,分别对应值的检索和值的分配。能通过 get 或 set 访问的属性包括自身属性(该对象的自身部分)和通过一个属性继承关系由另一个关联对象提供的继承属性。继承属性可以是关联对象的自身属性或关联对象的继承属性。 对象的每个自身属性都必须有一个不同于该对象的其它自身属性的键值。
在 ES 中,对象实际的语义是通过叫内部方法的算法来指定的。在 ES 引擎中,每一个对象都和定义了它运行时行为的一套内部方法相关联。这些内部方法并不是 ES 语言的一部分,它们是仅以说明为目的,被定义在本规范中。但是,在 ES 实现内的每一个对象的行为都必须表现出仿佛它是被这里的内部方法所指定的一样。 实现的具体方式是由 ES 实现决定的。
内部属性响应与之关联的对象的内部状态并常常被使用于 ES 规范算法中。内部属性并不是对象的属性,而且它们不能被继承。根据指定的内部属性规范,对象的状态可能由的 ES 语言类型 值或 ES 规范类型的值构成。除非显式指定,要不然内部属性会在对象被创建的过程中作为对象的一部分被分配,而不能被动态的添加给一个对象。除非显式指定,内部属性的初始值是 undefined。在本规范中,不同的算法都会创建出带内部属性的对象。然而,ES 语言并不直接提供一种将内部属性和一个对象相关联的方法。
在本规范中,内部方法和内部属性的名字会被闭合的双方括号 [[ ]] 包裹。
表 5 总结了在本规范中能够被应用于 ES 代码创建和操作的对象所使用的所有必须的基本内部方法。每一个对象都必须存在所有基本内部方法的算法。但是,对于这些内部方法来说,所有对象并没有必要使用相同的算法。
表 5 或其它类似表中的 “Signature” 列描述了每个内部方法的调用模式。这个调用模式总是包含一个描述性的用大括号包裹的参数名列表。如果一个参数的名字与一个 ES 类型名字相似,那么这个参数名描述了参数值的必要的类型。如果一个内部方法显示地返回了一个值,它的参数列表后面会有一符号 “→” 和一个返回值的类型名。被用在 signatures 中的类型名可以参考条款 6 augmented by the following additional names。“any” 表示值可以是任何 ES 语言类型。一个内部方法隐式地返回一个 完成记录。除了它的参数外,一个内部方法总是访问方法调用的目标对象。
通过 new 或者 super 运算符调用,创建一个对象。该内部方法的第一个参数是一个列表(包含了操作符的参数)。第二个参数是一个 new 对象操作符被首次应用的对象 。实现了这个内部方法的对象叫做构造器 。一个函数对象不一定是一个构造器,但一个非构造器的函数对象是没有 [[Construct]] 内部方法的。
一个 ES 引擎的对象的内部方法必须遵循下面指定的不变量的列表。在本规范中,普通 ES 对象和所有的标准外来对象会坚持这些不变量。ES Proxy 对象会通过运行时检查的方式来维持这些不变量 maintain these 不变量 by means of 运行时检查 on the result of traps invoked on the object.
由外来对象提供的实现也必须坚持这些不变量。违背这些不变量会导致 ES 代码有不可预测的行为和产生安全问题。然而,违背这些不变量不会被一个实现的内存安全所认可。
如果一个属性 P 被描述为一个携带有 Desc.[[Value]] 值为 v,以及 Desc.[[Writable]] 和 Desc.[[Configurable]] 值皆为 false 的数据属性,那么 the SameValue must be returned for the Desc.[[Value]] 特性 of the property on all future calls to [[GetOwnProperty]] ( P ).
If P's 特性 other than [[Writable]] may change over time or if the property might disappear, then P's [[Configurable]] 特性 must be true.
If the [[Writable]] 特性 may change from false to true, then the [[Configurable]] 特性 must be true.
If the target is non-extensible and P is non-existent, then all future calls to [[GetOwnProperty]] (P) on the target must describe P as non-existent (i.e. [[GetOwnProperty]] (P) must return undefined).
Note 2
As a consequence of the third invariant, if a property is described as a 数据属性 and it may return different values over time, then either or both of the Desc.[[Writable]] and Desc.[[Configurable]] 特性 must be true even if no mechanism to change the value is exposed via the other 内部方法.
[[DefineOwnProperty]] (P, Desc)
返回值的类型必须是 Boolean.
[[DefineOwnProperty]] 必须返回 false if P has previously been observed as a non-configurable 自身属性 of the target, unless either:
P is a non-configurable writable own 数据属性. A non-configurable writable 数据属性 can be changed into a non-configurable non-writable 数据属性.
[[DefineOwnProperty]] (P, Desc) 必须返回 false if target is non-extensible and P is a non-existent 自身属性. That is, a non-extensible target object cannot be extended with new properties.
[[HasProperty]] ( P )
返回值的类型必须是 Boolean.
If P was previously observed as a non-configurable data or accessor 自身属性 of the target, [[HasProperty]] must return true.
[[Get]] (P, Receiver)
If P was previously observed as a non-configurable, non-writable own 数据属性 of the target with value v, then [[Get]] must return the SameValue.
If P was previously observed as a non-configurable own 访问器属性 of the target whose [[Get]] 特性 is undefined, the [[Get]] operation must return undefined.
[[Set]] ( P, V, Receiver)
返回值的类型必须是 Boolean.
If P was previously observed as a non-configurable, non-writable own 数据属性 of the target, then [[Set]] 必须返回 false unless V is the SameValue as P's [[Value]] 特性.
If P was previously observed as a non-configurable own 访问器属性 of the target whose [[Set]] 特性 is undefined, the [[Set]] operation 必须返回 false.
[[Delete]] ( P )
返回值的类型必须是 Boolean.
If P was previously observed to be a non-configurable own data or 访问器属性 of the target, [[Delete]] 必须返回 false.
The returned list must not contain any duplicate entries.
The Type of each element of the returned List is either String or Symbol.
The returned List must contain at least the keys of all non-configurable 自身属性 that have previously been observed.
If the object is non-extensible, the returned List must contain only the keys of all 自身属性 of the object that are observable using [[GetOwnProperty]].
[[Construct]] ( )
返回值的类型必须是 Object.
6.1.7.4众所周知的内部对象
众所周知的内部对象是指,在本规范中被显式地引用的内置对象,通常会有一个 realm-specific 标志。除非另有说明,否则每个内部对象实际对应于一套相似对象的集合,one per realm.
在本规范中, 一个引用,例如 %name%,意味着该内部对象与当前的 realm 相关联, corresponding to the name. Determination of the current realm and its intrinsics is described in 8.3. 众所周知的内部对象见表 7。
列表类型用来说明在 new 表达式、函数调用和其他需要一个简单有序的值列表的算法中参数列表 (see 12.3.6) 的计算。列表类型的值是包含单个值的简单有序的列表元素的序列,这些序列可以是任意长度。 列表内的元素可以被基于 0 的索引随机访问。为了方便起见,一个类似数组的语法可以用来访问列表的元素。例如,arguments[2] 用来表示列表参数的第三个元素。
在规范文本和算法中,点标记被用来参考一个记录值的特殊字段。例如,如果 R 是上一个段落中的一个记录,那么 R.[[Field2]] 就是 “the field of R named [[Field2]]” 的简写。
Schema for commonly used Record field combinations may be named, and that name may be used as a prefix to a literal 记录值 to identify the specific kind of aggregations that is being described. 例如:PropertyDescriptor {[[Value]]: 42, [[Writable]]: false, [[Configurable]]: true}.
6.2.2集合规范类型和关系规范类型
The Set type is used to explain a collection of unordered elements for use in the 内存模型. Values of the Set type are simple collections of elements, where no element appears more than once. Elements may be added to and removed from Sets. Sets may be unioned, intersected, or subtracted from each other.
The Relation type is used to explain constraints on Sets. Values of the 关系类型 are Sets of ordered pairs of values from its value domain. 例如, a Relation on events is a set of ordered pairs of events. For a Relation R and two values a and b in the value domain of R, aRb is shorthand for saying the ordered pair (a, b) is a member of R. A Relation is least with respect to some conditions when it is the smallest Relation that satisfies those conditions.
A strict partial order is a 关系值 R that satisfies the following.
For all a, b, and c in R's domain:
It is not the case that aRa, and
If aRb and bRc, then aRc.
Note 1
The two properties above are called, in order, irreflexivity and transitivity.
A strict total order is a 关系值 R that satisfies the following.
For all a, b, and c in R's domain:
a is identical to b or aRb or bRa, and
It is not the case that aRa, and
If aRb and bRc, then aRc.
Note 2
The three properties above are called, in order, totality, irreflexivity, and transitivity.
6.2.3完成记录规范类型
The 完成类型 is a Record used to explain the runtime propagation of values and control flow 例如 the behaviour of statements (break, continue, return and throw) that perform nonlocal transfers of control.
Values of the 完成类型 are Record values whose fields are defined as by Table 8. Such values are referred to as 完成记录s.
Set the code 估值 state of asyncContext such that when 估值 is resumed with a Completioncompletion, the following steps of the 算法 that invoked Await will be performed, with completion available.
where all variables in the above steps, with the 异常 of completion, are ephemeral and visible only in the steps pertaining to Await.
Note
Await can be combined with the ? and ! prefixes, so that 例如
An Await fulfilled function is an anonymous 内置函数 that is used as part of the Await specification device to deliver the promise fulfillment value to the caller as a normal completion. Each Await fulfilled function has an [[AsyncContext]] 内部属性.
When an Await fulfilled function F is called with argument value, 执行如下:
Push asyncContext onto the 执行上下文 堆栈; asyncContext is now the 运行时执行上下文.
Resume the suspended 估值 of asyncContext using NormalCompletion(value) as the result of the operation that suspended it.
Assert: When we reach this step, asyncContext has already been removed from the 执行上下文 堆栈 and prevContext is the currently 运行时执行上下文.
Return undefined.
The length property of an Await fulfilled function is 1.
6.2.3.1.2Await Rejected Functions
An Await rejected function is an anonymous 内置函数 that is used as part of the Await specification device to deliver the promise rejection reason to the caller as an abrupt throw completion. Each Await rejected function has an [[AsyncContext]] 内部属性.
When an Await rejected function F is called with argument reason, 执行如下:
Push asyncContext onto the 执行上下文 堆栈; asyncContext is now the 运行时执行上下文.
Resume the suspended 估值 of asyncContext using Completion{[[Type]]: throw, [[Value]]: reason, [[Target]]: empty} as the result of the operation that suspended it.
Assert: When we reach this step, asyncContext has already been removed from the 执行上下文 堆栈 and prevContext is the currently 运行时执行上下文.
Return undefined.
The length property of an Await rejected function is 1.
6.2.3.2NormalCompletion
The 抽象操作 NormalCompletion with a single argument, 例如:
The object that may be created in step 5.a.ii is not accessible outside of the above 抽象操作 and the 普通对象 [[Get]] 内部方法. An 实现 might choose to avoid the actual creation of the object.
The object that may be created in step 6.a.ii is not accessible outside of the above 算法 and the 普通对象 [[Set]] 内部方法. An 实现 might choose to avoid the actual creation of that object.
The 数据块 规范类型 is used to describe a distinct and mutable sequence of byte-sized (8 bit) numeric values. A 数据块 value is created with a fixed number of bytes that each have the 初始值 0.
For notational convenience within this specification, an array-like syntax can be used to access the individual bytes of a 数据块 value. This notation presents a 数据块 value as a 0-origined integer-indexed sequence of bytes. 例如, if db is a 5 byte 数据块 value then db[2] can be used to access its 3rd byte.
A 数据块 that resides in memory that can be referenced from multiple 代理 concurrently is designated a 共享数据块. A 共享数据块 has an identity (for the purposes of equality testing 共享数据块 values) that is address-free: it is tied not to the virtual addresses the block is mapped to in any process, but to the set of locations in memory that the block represents. Two 数据块 are equal only if the sets of the locations they contain are equal; otherwise, they are not equal and the intersection of the sets of locations they contain is empty. Finally, Shared 数据块 can be distinguished from 数据块.
The 语义 of Shared 数据块 is defined using 共享数据块 events by the 内存模型. 抽象操作 below introduce 共享数据块 events and act as the interface between 估值 语义 and the event 语义 of the 内存模型. The events form a candidate execution, on which the 内存模型 acts as a filter. Please consult the 内存模型 for full 语义.
共享数据块 events are modeled by Records, defined in the 内存模型.
The following 抽象操作 are used 在本规范中 to operate upon 数据块 values:
6.2.7.1CreateByteDataBlock ( size )
When the 抽象操作 CreateByteDataBlock is called with integer argument size, 执行如下:
Let eventList be the [[EventList]] field of the element in execution.[[EventLists]] whose [[AgentSignifier]] is AgentSignifier().
Let bytes be a List of length 1 that contains a nondeterministically chosen byte value.
NOTE: In implementations, bytes is the result of a non-atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the 内存模型 to describe observable behaviour of hardware with weak consistency.
Let readEvent be ReadSharedMemory{ [[Order]]: "Unordered", [[NoTear]]: true, [[Block]]: fromBlock, [[ByteIndex]]: fromIndex, [[ElementSize]]: 1 }.
Append readEvent to eventList.
Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: bytes } to execution.[[ChosenValues]].
The 抽象操作 ToUint16 converts argument to one of 216 integer values in the range 0 through 216-1, inclusive. This 抽象操作 functions as follows:ToUint16 抽象操作将其参数 argument 转换为在闭区间 0 到 216-1 范围内的其中一个 216 位的整数值。此抽象操作运行如下:
Unlike the other ES integer conversion 抽象操作, ToUint8Clamp rounds rather than truncates non-integer values and does not convert +∞ to 0. ToUint8Clamp does “round half to even” tie-breaking. This differs from Math.round which does “round half up” tie-breaking.
Otherwise, let n, k, and s be integers such that k ≥ 1, 10k-1 ≤ s < 10k, the Number 值 for s × 10n-k is m, and k is as small as possible. Note that k is the number of digits in the decimal representation of s, that s is not divisible by 10, and that the least significant digit of s is not necessarily uniquely determined by these criteria.
Otherwise, let n, k, and s be integers such that k ≥ 1, 10k-1 ≤ s < 10k, the Number 值 for s × 10n-k is m, and k is as small as possible. If there are multiple possibilities for s, choose the value of s for which s × 10n-k is closest in value to m. If there are two such possible values of s, choose the one that is even. Note that k is the number of digits in the decimal representation of s and that s is not divisible by 10.
Note 3
Implementers of ES may find useful the paper and code written by David M. Gay for binary-to-decimal conversion of floating-point numbers:
The 抽象操作 CanonicalNumericIndexString returns argument converted to a 数字值 if it is a String representation of a Number that would be produced by ToString, or the string "-0". Otherwise, it returns undefined. This 抽象操作 functions as follows:
If x and y are both the same Symbol 值, return true; otherwise, return false.
If x and y are the same Object value, return true. Otherwise, return false.
7.2.13抽象关系比较
该比较 x < y, 其操作数 x 和 y 的都是 ES 语言值,会返回 true 或 false 或 undefined (表明至少有一个操作数是 NaN). In addition to x and y the 算法 takes a Boolean flag named LeftFirst as a parameter. The flag is used to control the order in which operations with potentially visible side-effects are performed upon x and y. It is necessary because ES specifies left to right 估值 of expressions. The 默认值 of LeftFirst is true and indicates that the x parameter corresponds to an expression that occurs to the left of the y parameter's corresponding expression. If LeftFirst is false, the reverse is the case and operations must be performed upon y before x. Such a comparison is performed as follows:
Let k be the smallest nonnegative integer such that the 代码单元 at index k within px is different from the 代码单元 at index k within py. (There must be such a k, for neither String is a prefix of the other.)
Let m be the integer that is the 数字值 of the 代码单元 at index k within px.
Let n be the integer that is the 数字值 of the 代码单元 at index k within py.
If m < n, return true. Otherwise, return false.
Else,
NOTE: Because px and py are primitive values 估值 order is not important.
If the 数学值 of nx is less than the 数学值 of ny—note that these mathematical values are both finite and not both zero—return true. Otherwise, return false.
Note 1
Step 3 differs from step 7 in the 算法 for 加运算符 + (12.8.3) by using the 逻辑与运算 instead of the 逻辑或运算.
Note 2
The comparison of Strings uses a simple lexicographic ordering on sequences of 代码单元 values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the Unicode specification. Therefore String values that are canonically equal according to the Unicode standard could test as unequal. In effect this 算法 assumes that both Strings are already in normalized form. Also, note that for strings containing supplementary characters, lexicographic ordering on sequences of UTF-16 代码单元 values differs from that on sequences of 码点 values.
7.2.14抽象相等比较
该比较 x == y,其操作数 x 和 y 都是 ES 语言值,会返回 true 或 false。执行如下:
This 算法 differs from the SameValue 算法 in its treatment of signed zeroes and NaNs.该算法与 SameValue 的算法的区别在于有符号 0 和 NaNs 的比较。在本算法中,+0 和-0 是相等的,但 NaN 的比较是不相等的,而 SameValue 的算法反之。
7.3对象操作
7.3.1Get ( O, P )
抽象操作 Get 用来检索对象上一个指定的属性的值。该操作会携带参数 O 和 P (O 是一个对象,P 是一个属性键)。执行如下:
The 抽象操作 GetMethod is used to get the value of a specific property of an ES 语言值 when the value of the property is expected to be a function. The operation is called with arguments V and P where V is the ES 语言值, P is the property key. This 抽象操作 执行如下:抽象操作 GetMethod 用来获取一个 ES 语言值的一个指定的属性的值(当该属性的值被期待是一个函数时)。该操作会被以携带参数 V 和 P (V 是一个 ES 语言值,P 是一个属性键)的形式调用。执行如下:
The 抽象操作 CreateListFromArrayLike is used to create a List value whose elements are provided by the indexed properties of an array-like object, obj. The 可选参数 elementTypes is a List containing the names of ES 语言类型 that are allowed for element values of the List that is created. This 抽象操作 执行如下:
If elementTypes is not present, set elementTypes to « Undefined, Null, Boolean, String, Symbol, Number, Object ».
If Type(next) is not an element of elementTypes, 抛出一个 TypeError 异常.
Append next as the last element of list.
Set index to index + 1.
Return list.
7.3.18Invoke ( V, P [ , argumentsList ] )
The 抽象操作 Invoke is used to call a method property of an ES 语言值. The operation is called with arguments V, P, and optionally argumentsList where V serves as both the lookup point for the property and the this value of the call, P is the property key, and argumentsList is the list of arguments values passed to the method. If argumentsList is not present, a new empty List is used as its value. This 抽象操作 执行如下:
The 抽象操作 OrdinaryHasInstance implements the default 算法 for determining if an object O inherits from the instance object inheritance path provided by 构造器C. This 抽象操作 执行如下:
7.3.20SpeciesConstructor ( O, defaultConstructor )
The 抽象操作 SpeciesConstructor is used to retrieve the 构造器 that should be used to create new objects that are derived from the argument object O. The defaultConstructor argument is the 构造器 to use if a 构造器 @@species property cannot be found starting from O. This 抽象操作 执行如下:
Order the elements of properties so they are in the same relative order as would be produced by the 迭代器 that would be returned if the EnumerateObjectProperties 内部方法 were invoked with O.
The 抽象操作 IteratorStep with argument iteratorRecord requests the next value from iteratorRecord.[[迭代器]] by calling iteratorRecord.[[NextMethod]] and returns either false indicating that the 迭代器 has reached its end or the IteratorResult object if a next value is available. IteratorStep 执行如下:
The 抽象操作 IteratorClose with arguments iteratorRecord and completion is used to notify an 迭代器 that it should perform any actions it would normally perform when it has reached its completed state:
The 抽象操作 AsyncIteratorClose with arguments iteratorRecord and completion is used to notify an async 迭代器 that it should perform any actions it would normally perform when it has reached its completed state:
The 抽象操作 CreateIterResultObject with arguments value and done creates an object that supports the IteratorResult interface by performing the following steps:
The 抽象操作 CreateListIteratorRecord with argument list creates an 迭代器 (25.1.1.2) object record whose next method returns the successive elements of list. It 执行如下:
A 词法环境 is a 规范类型 used to define the association of Identifiers to specific variables and functions based upon the 词法巢式结构 of ES 代码.一个词法环境由一个环境记录和可能为空的外部词法环境引用构成。通常词法环境会与一些特定的 ES 代码的句法结构(诸如 a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement)相联系,且这样的代码每次执行都会有一个新的词法环境被创建。
函数环境是一个响应 ES 函数对象调用的词法环境。函数环境可能会建立一个新的 this 绑定。一个函数环境也会捕获通过 super 方法调用产生的必要的状态。
词法环境和环境记录值是纯粹的规范机制,不需要与 ES 实现的 any specific artefact 保持一致。ES 程序不可能直接访问或者操作这些值。
8.1.1环境记录
在本规范中,共有两种主要的环境记录值被使用:声明环境记录和对象环境记录 。声明环境记录用于定义 ES 语言句法元素(直接将标识符绑定和 ES 语言值相关联)的效果,例如 FunctionDeclarations, VariableDeclarations, and Catch clauses 。对象环境记录用于定义那些将标识符绑定与一些对象的属性相关联的 ES 元素的效果,例如 WithStatement。全局环境记录和函数环境记录是 specializations that are used for specifically for Script global declarations and for top-level declarations within functions。
出于规范的目的,环境记录值是 Record 规范类型的值,且可以理解为面向对象中的一个简单继承结构,其中环境记录是一个抽象类,有 3 个具体亚类,分别为声明环境记录、对象环境记录和全局环境记录。函数环境记录和模块环境记录是声明环境记录的亚类。这个抽象类包含了定义在表 14 中的抽象规范方法。针对每一个具体的亚类,这些抽象方法都有不同的具体算法。
表 14: 环境记录的抽象方法
Method
Purpose
HasBinding(N)
判断环境记录是否有一个对字符串值 N 的绑定。如果有该绑定则返回 true,反之返回 false。(其中字符串 N 是标识符文本。)
CreateMutableBinding(N, D)
在一个环境记录中创建一个新的且未初始化的可变绑定。其中字符串值 N 是绑定名称的文本。如果布尔类型的参数 D 的值为 true ,则该绑定在后续操作中可以被删除。
CreateImmutableBinding(N, S)
在一个环境记录中创建一个新的且未初始化的不可变绑定。其中字符串值 N 是绑定名的文本。如果布尔类型的参数 S 的值为 true ,则在它被初始化之后会尝试设置它时会抛出一个异常。不管引用那个绑定的操作是不是在严格模式下。
InitializeBinding(N, V)
在一个环境记录中设置一个已经存在但未初始化的绑定。字符串值 N 是绑定名的文本。V 是绑定的值,且是任一 ES 语言类型的值。
SetMutableBinding(N, V, S)
在一个环境记录中设置一个已经存在的可变绑定的值。字符串值 N 是绑定名的文本。V 是绑定的值,且是任一 ES 语言类型的值。S 是一个布尔标志。如果 S 为 true 且这个绑定不能被设置,那么将抛出一个 TypeError 异常。
GetBindingValue(N, S)
从一个环境记录中返回一个已经存在的绑定的值。字符串值 N 是绑定名的文本。S 用于指定引用是否发生在严格模式代码下 or that otherwise require 严格模式引用 语义。如果 S 的值为 true 并且该绑定不存在,则抛出一个 ReferenceError 异常。如果绑定存在且未被初始化,那么,不管 S 的值是什么,都会抛出一个 ReferenceError 异常。
DeleteBinding(N)
从环境记录中删除一个绑定。字符串值 N 是绑定名的文本。如果 N 指定的绑定存在,那么会将其删除并返回 true。如果绑定存在但无法删除则返回 false。如果绑定不存在则返回 true。
Let envRec be the declarative 环境记录 for which the method was invoked.
If envRec has a binding for the name that is the value of N, return true.
Return false.
8.1.1.1.2CreateMutableBinding ( N, D )
声明环境记录的具体环境记录方法 CreateMutableBinding 用来创建一个新的且绑定名 N 未被初始化的可变绑定。一个绑定名 N 必须是原来不存在于这个环境记录中的。如果布尔类型的参数 D 的值为 true ,则该绑定在后续操作中可以被删除。
Let envRec be the declarative 环境记录 for which the method was invoked.
Assert: envRec does not already have a binding for N.
Create a mutable binding in envRec for N and record that it is uninitialized. If D is true, record that the newly created binding may be deleted by a subsequent DeleteBinding call.
The concrete 环境记录 method CreateImmutableBinding for 声明式环境记录 creates a new immutable binding for the name N that is uninitialized. A binding must not already exist in this 环境记录 for N. If the Boolean argument S has the value true the new binding is marked as a strict binding.
Let envRec be the declarative 环境记录 for which the method was invoked.
Assert: envRec does not already have a binding for N.
Create an immutable binding in envRec for N and record that it is uninitialized. If S is true, record that the newly created binding is a strict binding.
The concrete 环境记录 method InitializeBinding for 声明式环境记录 is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. An uninitialized binding for N must already exist.
Let envRec be the declarative 环境记录 for which the method was invoked.
Assert: envRec must have an uninitialized binding for N.
Set the bound value for N in envRec to V.
Record that the binding for N in envRec has been initialized.
The concrete 环境记录 method SetMutableBinding for 声明式环境记录 attempts to change the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. A binding for N normally already exists, but in rare cases it may not. If the binding is an immutable binding, a TypeError is thrown if S is true.
Let envRec be the declarative 环境记录 for which the method was invoked.
An example of ES 代码 that results in a missing binding at step 2 is:
function f(){eval("var x; x = (delete x, 0);")}
8.1.1.1.6GetBindingValue ( N, S )
The concrete 环境记录 method GetBindingValue for 声明式环境记录 simply returns the value of its bound identifier whose name is the value of the argument N. If the binding exists but is uninitialized a ReferenceError is thrown, regardless of the value of S.
Let envRec be the declarative 环境记录 for which the method was invoked.
The concrete 环境记录 method CreateMutableBinding for 对象环境记录 creates in an 环境记录's associated binding object a property whose name is the String 值 and initializes it to the value undefined. If Boolean argument D has the value true the new property's [[Configurable]] 特性 is set to true; otherwise it is set to false.
Let envRec be the object 环境记录 for which the method was invoked.
Normally envRec will not have a binding for N but if it does, the 语义 of DefinePropertyOrThrow may result in an existing binding being replaced or shadowed or cause an abrupt completion to be returned.
8.1.1.2.3CreateImmutableBinding ( N, S )
The concrete 环境记录 method CreateImmutableBinding is never used within this specification in association with 对象环境记录.
8.1.1.2.4InitializeBinding ( N, V )
The concrete 环境记录 method InitializeBinding for 对象环境记录 is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. An uninitialized binding for N must already exist.
Let envRec be the object 环境记录 for which the method was invoked.
Assert: envRec must have an uninitialized binding for N.
Record that the binding for N in envRec has been initialized.
Return ? envRec.SetMutableBinding(N, V, false).
Note
在本规范中, all uses of CreateMutableBinding for 对象环境记录 are immediately followed by a call to InitializeBinding for the same name. Hence, implementations do not need to explicitly track the initialization state of individual object 环境记录 bindings.
8.1.1.2.5SetMutableBinding ( N, V, S )
The concrete 环境记录 method SetMutableBinding for 对象环境记录 attempts to set the value of the 环境记录's associated binding object's property whose name is the value of the argument N to the value of argument V. A property named N normally already exists but if it does not or is not currently writable, error handling is determined by the value of the Boolean argument S.
Let envRec be the object 环境记录 for which the method was invoked.
The concrete 环境记录 method GetBindingValue for 对象环境记录 returns the value of its associated binding object's property whose name is the String 值 of the argument identifier N. The property should already exist but if it does not the result depends upon the value of the S argument:
Let envRec be the object 环境记录 for which the method was invoked.
The concrete 环境记录 method DeleteBinding for 对象环境记录 can only delete bindings that correspond to properties of the environment object whose [[Configurable]] 特性 have the value true.
Let envRec be the object 环境记录 for which the method was invoked.
Let bindings be the binding object for envRec.
Return ? bindings.[[Delete]](N).
8.1.1.2.8HasThisBinding ( )
Regular 对象环境记录 do not provide a this binding.
Return false.
8.1.1.2.9HasSuperBinding ( )
Regular 对象环境记录 do not provide a super binding.
Return false.
8.1.1.2.10WithBaseObject ( )
对象环境记录 return undefined as their WithBaseObject unless their withEnvironment flag is true.
Let envRec be the object 环境记录 for which the method was invoked.
If the withEnvironment flag of envRec is true, return the binding object for envRec.
Otherwise, return undefined.
8.1.1.3函数环境记录
函数环境记录是一个用于表示一个函数顶层作用域的声明环境记录,如何这个函数不是一个箭头函数,那么它会提供一个 this 绑定。如何一个函数不是箭头函数 且引用了 super,那么它的函数环境记录也会包含这个(在函数内用于执行 super 方法调用)状态。
This is the this value used for this invocation of the function.
[[ThisBindingStatus]]
"lexical" | "initialized" | "uninitialized"
If the value is "lexical", this is an ArrowFunction and does not have a local this value.
[[FunctionObject]]
Object
The 函数对象 whose invocation caused this 环境记录 to be created.
[[HomeObject]]
Object | undefined
If the associated function has super property accesses and is not an ArrowFunction, [[HomeObject]] is the object that the function is bound to as a method. The 默认值 for [[HomeObject]] is undefined.
[[NewTarget]]
Object | undefined
If this 环境记录 was created by the [[Construct]] 内部方法, [[NewTarget]] is the value of the [[Construct]] newTarget parameter. Otherwise, its value is undefined.
函数环境记录 support all of the declarative 环境记录 methods listed in Table 14 and share the same specifications for all of those methods except for HasThisBinding and HasSuperBinding. In addition, 函数环境记录 support the methods listed in Table 16:
Table 16: Additional Methods of 函数环境记录
Method
Purpose
BindThisValue(V)
Set the [[ThisValue]] and record that it has been initialized.
GetThisBinding()
Return the value of this 环境记录's this binding. Throws a ReferenceError if the this binding has not been initialized.
GetSuperBase()
Return the object that is the base for super property accesses bound in this 环境记录. The object is derived from this 环境记录's [[HomeObject]] field. The value undefined indicates that super property accesses will produce runtime errors.
The behaviour of the additional concrete specification methods for 函数环境记录 is defined by the following 算法:
8.1.1.3.1BindThisValue ( V )
Let envRec be the 函数环境记录 for which the method was invoked.
Assert: envRec.[[ThisBindingStatus]] is not "lexical".
If envRec.[[ThisBindingStatus]] is "initialized", 抛出一个 ReferenceError 异常.
Set envRec.[[ThisValue]] to V.
Set envRec.[[ThisBindingStatus]] to "initialized".
Return V.
8.1.1.3.2HasThisBinding ( )
Let envRec be the 函数环境记录 for which the method was invoked.
If envRec.[[ThisBindingStatus]] is "lexical", return false; otherwise, return true.
8.1.1.3.3HasSuperBinding ( )
Let envRec be the 函数环境记录 for which the method was invoked.
If envRec.[[ThisBindingStatus]] is "lexical", return false.
If envRec.[[HomeObject]] has the value undefined, return false; otherwise, return true.
8.1.1.3.4GetThisBinding ( )
Let envRec be the 函数环境记录 for which the method was invoked.
Assert: envRec.[[ThisBindingStatus]] is not "lexical".
If envRec.[[ThisBindingStatus]] is "uninitialized", 抛出一个 ReferenceError 异常.
Return envRec.[[ThisValue]].
8.1.1.3.5GetSuperBase ( )
Let envRec be the 函数环境记录 for which the method was invoked.
Let home be envRec.[[HomeObject]].
If home has the value undefined, return undefined.
Determines if the argument identifier has a binding in this 环境记录 that was created using a lexical declaration 例如 a LexicalDeclaration or a ClassDeclaration.
HasRestrictedGlobalProperty (N)
Determines if the argument is the name of a 全局对象 property that may not be shadowed by a global lexical binding.
CanDeclareGlobalVar (N)
Determines if a corresponding CreateGlobalVarBinding call would succeed if called for the same argument N.
CanDeclareGlobalFunction (N)
Determines if a corresponding CreateGlobalFunctionBinding call would succeed if called for the same argument N.
CreateGlobalVarBinding(N, D)
Used to create and initialize to undefined a global var binding in the [[ObjectRecord]] component of a global 环境记录. The binding will be a mutable binding. The corresponding 全局对象 property will have 特性 values appropriate for a var. The String 值 N is the bound name. If D is true the binding may be deleted. Logically equivalent to CreateMutableBinding followed by a SetMutableBinding but it allows var declarations to receive special treatment.
CreateGlobalFunctionBinding(N, V, D)
Create and initialize a global function binding in the [[ObjectRecord]] component of a global 环境记录. The binding will be a mutable binding. The corresponding 全局对象 property will have 特性 values appropriate for a function. The String 值 N is the bound name. V is the initialization value. If the Boolean argument D is true the binding may be deleted. Logically equivalent to CreateMutableBinding followed by a SetMutableBinding but it allows 函数声明 to receive special treatment.
The behaviour of the concrete specification methods for 全局环境记录 is defined by the following 算法.
8.1.1.4.1HasBinding ( N )
The concrete 环境记录 method HasBinding for 全局环境记录 simply determines if the argument identifier is one of the 标识符 bound by the record:
Let envRec be the global 环境记录 for which the method was invoked.
Let DclRec be envRec.[[DeclarativeRecord]].
If DclRec.HasBinding(N) is true, return true.
Let ObjRec be envRec.[[ObjectRecord]].
Return ? ObjRec.HasBinding(N).
8.1.1.4.2CreateMutableBinding ( N, D )
The concrete 环境记录 method CreateMutableBinding for 全局环境记录 creates a new mutable binding for the name N that is uninitialized. The binding is created in the associated DeclarativeRecord. A binding for N must not already exist in the DeclarativeRecord. If Boolean argument D has the value true the new binding is marked as being subject to deletion.
Let envRec be the global 环境记录 for which the method was invoked.
Let DclRec be envRec.[[DeclarativeRecord]].
If DclRec.HasBinding(N) is true, 抛出一个 TypeError 异常.
Return DclRec.CreateMutableBinding(N, D).
8.1.1.4.3CreateImmutableBinding ( N, S )
The concrete 环境记录 method CreateImmutableBinding for 全局环境记录 creates a new immutable binding for the name N that is uninitialized. A binding must not already exist in this 环境记录 for N. If the Boolean argument S has the value true the new binding is marked as a strict binding.
Let envRec be the global 环境记录 for which the method was invoked.
Let DclRec be envRec.[[DeclarativeRecord]].
If DclRec.HasBinding(N) is true, 抛出一个 TypeError 异常.
Return DclRec.CreateImmutableBinding(N, S).
8.1.1.4.4InitializeBinding ( N, V )
The concrete 环境记录 method InitializeBinding for 全局环境记录 is used to set the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. An uninitialized binding for N must already exist.
Let envRec be the global 环境记录 for which the method was invoked.
Let DclRec be envRec.[[DeclarativeRecord]].
If DclRec.HasBinding(N) is true, then
Return DclRec.InitializeBinding(N, V).
Assert: If the binding exists, it must be in the object 环境记录.
Let ObjRec be envRec.[[ObjectRecord]].
Return ? ObjRec.InitializeBinding(N, V).
8.1.1.4.5SetMutableBinding ( N, V, S )
The concrete 环境记录 method SetMutableBinding for 全局环境记录 attempts to change the bound value of the current binding of the identifier whose name is the value of the argument N to the value of argument V. If the binding is an immutable binding, a TypeError is thrown if S is true. A property named N normally already exists but if it does not or is not currently writable, error handling is determined by the value of the Boolean argument S.
Let envRec be the global 环境记录 for which the method was invoked.
Let DclRec be envRec.[[DeclarativeRecord]].
If DclRec.HasBinding(N) is true, then
Return DclRec.SetMutableBinding(N, V, S).
Let ObjRec be envRec.[[ObjectRecord]].
Return ? ObjRec.SetMutableBinding(N, V, S).
8.1.1.4.6GetBindingValue ( N, S )
The concrete 环境记录 method GetBindingValue for 全局环境记录 returns the value of its bound identifier whose name is the value of the argument N. If the binding is an uninitialized binding 抛出一个 ReferenceError 异常. A property named N normally already exists but if it does not or is not currently writable, error handling is determined by the value of the Boolean argument S.
Let envRec be the global 环境记录 for which the method was invoked.
Let DclRec be envRec.[[DeclarativeRecord]].
If DclRec.HasBinding(N) is true, then
Return DclRec.GetBindingValue(N, S).
Let ObjRec be envRec.[[ObjectRecord]].
Return ? ObjRec.GetBindingValue(N, S).
8.1.1.4.7DeleteBinding ( N )
The concrete 环境记录 method DeleteBinding for 全局环境记录 can only delete bindings that have been explicitly designated as being subject to deletion.
Let envRec be the global 环境记录 for which the method was invoked.
Let DclRec be envRec.[[DeclarativeRecord]].
If DclRec.HasBinding(N) is true, then
Return DclRec.DeleteBinding(N).
Let ObjRec be envRec.[[ObjectRecord]].
Let globalObject be the binding object for ObjRec.
If N is an element of varNames, remove that element from the varNames.
Return status.
Return true.
8.1.1.4.8HasThisBinding ( )
Return true.
8.1.1.4.9HasSuperBinding ( )
Return false.
8.1.1.4.10WithBaseObject ( )
全局环境记录 always return undefined as their WithBaseObject.
Return undefined.
8.1.1.4.11GetThisBinding ( )
Let envRec be the global 环境记录 for which the method was invoked.
Return envRec.[[GlobalThisValue]].
8.1.1.4.12HasVarDeclaration ( N )
The concrete 环境记录 method HasVarDeclaration for 全局环境记录 determines if the argument identifier has a binding in this record that was created using a VariableStatement or a FunctionDeclaration:
Let envRec be the global 环境记录 for which the method was invoked.
Let varDeclaredNames be envRec.[[VarNames]].
If varDeclaredNames contains N, return true.
Return false.
8.1.1.4.13HasLexicalDeclaration ( N )
The concrete 环境记录 method HasLexicalDeclaration for 全局环境记录 determines if the argument identifier has a binding in this record that was created using a lexical declaration 例如 a LexicalDeclaration or a ClassDeclaration:
Let envRec be the global 环境记录 for which the method was invoked.
Let DclRec be envRec.[[DeclarativeRecord]].
Return DclRec.HasBinding(N).
8.1.1.4.14HasRestrictedGlobalProperty ( N )
The concrete 环境记录 method HasRestrictedGlobalProperty for 全局环境记录 determines if the argument identifier is the name of a property of the 全局对象 that must not be shadowed by a global lexical binding:
Let envRec be the global 环境记录 for which the method was invoked.
Let ObjRec be envRec.[[ObjectRecord]].
Let globalObject be the binding object for ObjRec.
Let existingProp be ? globalObject.[[GetOwnProperty]](N).
If existingProp is undefined, return false.
If existingProp.[[Configurable]] is true, return false.
Return true.
Note
Properties may exist upon a 全局对象 that were directly created rather than being declared using a var or function declaration. A global lexical binding may not be created that has the same name as a non-configurable property of the 全局对象. The global property undefined is an example of such a property.
8.1.1.4.15CanDeclareGlobalVar ( N )
The concrete 环境记录 method CanDeclareGlobalVar for 全局环境记录 determines if a corresponding CreateGlobalVarBinding call would succeed if called for the same argument N. Redundant var declarations and var declarations for pre-existing 全局对象 properties are allowed.
Let envRec be the global 环境记录 for which the method was invoked.
Let ObjRec be envRec.[[ObjectRecord]].
Let globalObject be the binding object for ObjRec.
The concrete 环境记录 method CanDeclareGlobalFunction for 全局环境记录 determines if a corresponding CreateGlobalFunctionBinding call would succeed if called for the same argument N.
Let envRec be the global 环境记录 for which the method was invoked.
Let ObjRec be envRec.[[ObjectRecord]].
Let globalObject be the binding object for ObjRec.
Let existingProp be ? globalObject.[[GetOwnProperty]](N).
If existingProp is undefined, return ? IsExtensible(globalObject).
If existingProp.[[Configurable]] is true, return true.
If IsDataDescriptor(existingProp) is true and existingProp has 特性 values {[[Writable]]: true, [[Enumerable]]: true}, return true.
Return false.
8.1.1.4.17CreateGlobalVarBinding ( N, D )
The concrete 环境记录 method CreateGlobalVarBinding for 全局环境记录 creates and initializes a mutable binding in the associated object 环境记录 and records the bound name in the associated [[VarNames]] List. If a binding already exists, it is reused and assumed to be initialized.
Let envRec be the global 环境记录 for which the method was invoked.
Let ObjRec be envRec.[[ObjectRecord]].
Let globalObject be the binding object for ObjRec.
The concrete 环境记录 method CreateGlobalFunctionBinding for 全局环境记录 creates and initializes a mutable binding in the associated object 环境记录 and records the bound name in the associated [[VarNames]] List. If a binding already exists, it is replaced.
Let envRec be the global 环境记录 for which the method was invoked.
Let ObjRec be envRec.[[ObjectRecord]].
Let globalObject be the binding object for ObjRec.
Let existingProp be ? globalObject.[[GetOwnProperty]](N).
If existingProp is undefined or existingProp.[[Configurable]] is true, then
Let desc be the PropertyDescriptor{[[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D}.
Else,
Let desc be the PropertyDescriptor{[[Value]]: V }.
Global 函数声明 are always represented as 自身属性 of the 全局对象. If possible, an existing 自身属性 is reconfigured to have a standard set of 特性 values. Steps 8-9 are equivalent to what calling the InitializeBinding concrete method would do and if globalObject is a Proxy will produce the same sequence of Proxy trap calls.
8.1.1.5模块环境记录
模块环境记录是一个声明环境记录,用于表示一个 ES 模块 的外层作用域。除了正常的可变和不可变的绑定之外,模块环境记录还提供不可变的 import 绑定(可以提供对一个存在于另一个环境记录的目标绑定的间接访问)。
模块环境记录支持所有声明环境记录的方法(见表 14)和共享除了 GetBindingValue, DeleteBinding, HasThisBinding and GetThisBinding 这些的所有方法的相同规范。另外,模块环境记录支持列在表 19 中的方法:
表 19: 模块环境记录的额外方法
Method
Purpose
CreateImportBinding(N, M, N2)
Create an immutable indirect binding in a module 环境记录. The String 值 N is the text of the bound name. M is a Module Record, and N2 is a binding that exists in M's module 环境记录.
The behaviour of the additional concrete specification methods for 模块环境记录 are defined by the following 算法:
8.1.1.5.1GetBindingValue ( N, S )
The concrete 环境记录 method GetBindingValue for 模块环境记录 returns the value of its bound identifier whose name is the value of the argument N. However, if the binding is an indirect binding the value of the target binding is returned. If the binding exists but is uninitialized a ReferenceError is thrown.
模块环境记录 are only used within strict code and an 早期错误 rule prevents the delete 运算符, in strict code, from being applied to a Reference that would resolve to a module 环境记录 binding. See 12.5.3.1.
8.1.1.5.3HasThisBinding ( )
模块环境记录 provide a this binding.
Return true.
8.1.1.5.4GetThisBinding ( )
Return undefined.
8.1.1.5.5CreateImportBinding ( N, M, N2 )
The concrete 环境记录 method CreateImportBinding for 模块环境记录 creates a new initialized immutable indirect binding for the name N. A binding must not already exist in this 环境记录 for N. M is a Module Record, and N2 is the name of a binding that exists in M's module 环境记录. Accesses to the value of the new binding will indirectly access the bound value of the target binding.
Let envRec be the module 环境记录 for which the method was invoked.
Assert: envRec does not already have a binding for N.
The 抽象操作 GetIdentifierReference is called with a 词法环境lex, a String name, and a Boolean flag strict. The value of lex may be null. When called, the following steps are performed:
If lex is the value null, then
Return a value of type Reference whose base value component is undefined, whose referenced name component is name, and whose strict reference flag is strict.
Return a value of type Reference whose base value component is envRec, whose referenced name component is name, and whose strict reference flag is strict.
Else,
Let outer be the value of lex's outer environment reference.
Template objects are canonicalized separately for each realm using its Realm Record's [[TemplateMap]]. Each [[Site]] value is a 解析节点 that is a TemplateLiteral. The associated [[Array]] value is the corresponding template object that is passed to a tag function.
Note
Once a 解析节点 becomes unreachable, the corresponding [[Array]] is also unreachable, and it would be unobservable if an 实现 removed the pair from the [[TemplateMap]] list.
[[HostDefined]]
Any, 默认值 is undefined.
Field reserved for use by 宿主环境 that need to associate additional information with a Realm Record.
Set fields of intrinsics with the values listed in Table 7 that have not already been handled above. The field names are the names listed in column one of the table. The value of each field is a new object value fully and recursively populated with property values as defined by the specification of each object in clauses 18-26. All object property values are newly created object values. All values that are 内置函数对象 are created by performing CreateBuiltinFunction(<steps>, <slots>, realmRec, <prototype>) where <steps> is the definition of that function provided by this specification, <slots> is a list of the names, if any, of the function's specified 内部属性, and <prototype> is the specified value of the function's [[Prototype]] 内部属性. The creation of the intrinsics and their properties must be ordered to avoid any dependencies upon objects that have not yet been created.
Let desc be the fully populated 数据属性 descriptor for the property containing the specified 特性 for the property. For properties listed in 18.2, 18.3, or 18.4 the value of the [[Value]] 特性 is the corresponding 内部对象 from realmRec.
Any state needed to perform, suspend, and resume 估值 of the code associated with this 执行上下文.
Function
If this 执行上下文 is evaluating the code of a 函数对象, then the value of this component is that 函数对象. If the context is evaluating the code of a Script or Module, the value is null.
The Realm Record from which associated code accesses ES resources.
ScriptOrModule
The Module Record or 脚本记录 from which associated code originates. If there is no originating script or module, as is the case for the original 执行上下文 created in InitializeHostDefinedRealm, the value is null.
运行时执行上下文对代码的评估可以在该规范中定义的各个点上暂停。一旦运行时执行上下文被暂停,一个不同的执行上下文就可能成为运行时执行上下文,并开始评估其代码。在稍后的时间内,一个被暂停的执行上下文可能再次成为运行时执行上下文,并继续在其先前暂停的位置上对其执行代码进行评估。在执行上下文中运行时执行上下文状态的转换通常以类似于后进先出的方式出现在堆栈中。然而,一些 ES 功能需要运行时执行上下文非后进先出的过渡。
The GeneratorObject that this 执行上下文 is evaluating.
在大多数情况下,只有运行时执行上下文(执行上下文堆栈的顶部)是被本规范中的算法所直接操作的。 Hence when the terms “LexicalEnvironment”, and “VariableEnvironment” are used without qualification they are in reference to those components of the 运行时执行上下文.
An 执行上下文 is purely a specification mechanism and need not correspond to any particular artefact of an ES 实现. It is impossible for ES 代码 to directly access or observe an 执行上下文.执行上下文是一个纯粹的规范机制,不需要对应于任何 ES 实现指定的 artefact。对于 ES 代码来说,直接访问或观察一个执行上下文是不可能的。
8.3.1GetActiveScriptOrModule ( )
The GetActiveScriptOrModule 抽象操作 is used to determine the running script or module, based on the 运行时执行上下文. GetActiveScriptOrModule 执行如下:
Let ec be the topmost 执行上下文 on the 执行上下文 堆栈 whose ScriptOrModule component is not null.
If no such 执行上下文 exists, return null. Otherwise, return ec's ScriptOrModule component.
8.3.2ResolveBinding ( name [ , env ] )
The ResolveBinding 抽象操作 is used to determine the binding of name passed as a String 值. The 可选参数 env can be used to explicitly provide the 词法环境 that is to be searched for the binding. During execution of ES 代码, ResolveBinding is performed using the following 算法:
If env is not present or if env is undefined, then
当在当前的进度中没有其它 ES 计算时,Job 是一个用来初始化一个 ES 计算的抽象操作。可以定义 Job 抽象操作以接受任意一组作业参数。
A Pending Job is an internal Record whose fields are specified in Table. Once execution of a Job is initiated, the Job always executes to completion. No other Job may be initiated until the currently running Job completes. However, the currently running Job or external events may cause the enqueuing of additional Pending Jobs that may be initiated sometime after completion of the currently running Job.只有在没有运行时执行上下文和执行上下文堆栈是空的情况下才能启动一个 Job 的执行。一个暂停的 Job 是一个 Job 的未来执行请求。暂停的 Job 是一个内部记录,其字段在表 24 中指定。一旦开始执行一个 Job,Job 会始终执行直到完成。在当前运行的 Job 完成之前,不可以启动其他 Job。然而,当前正在运行的 Job 或外部事件可能会导致额外的暂停的 Job(可能是当前正在运行的 Job 完成后的某个时候开始执行)入队。
Push newContext onto the 执行上下文 堆栈; newContext is now the 运行时执行上下文.
If the host requires use of an 外来对象 to serve as realm's 全局对象, let global be such an object created in an 实现-defined manner. Otherwise, let global be undefined, indicating that an 普通对象 should be created as the 全局对象.
If the host requires that the this binding in realm's global scope return an object other than the 全局对象, let thisValue be such an object created in an 实现-defined manner. Otherwise, let thisValue be undefined, indicating that realm's global this binding should be the 全局对象.
In an 实现-dependent manner, obtain the ES source texts (see clause 10) and any associated host-defined values for zero or more ES 脚本 and/or ES 模块. For each such 源文本 and hostDefined, do
代理包括一套 ES 的执行上下文,一个执行上下文堆栈,一个运行时执行上下文,一组命名的 Job 队列,一个代理记录,和一个执行线程。除执行线程外,代理的组成部分完全属于该代理。
An agent's executing thread executes the jobs in the agent's job queues on the agent's 执行上下文 independently of other 代理, except that an executing thread may be used as the executing thread by multiple 代理, provided none of the 代理 sharing the thread have an Agent Record whose [[CanBlock]] property is true.
The 默认值 computed for the isLittleEndian parameter when it is needed by the 算法 GetValueFromBuffer and SetValueInBuffer. The choice is 实现-dependent and should be the alternative that is most efficient for the 实现. Once the value has been observed it cannot change.
Once the values of [[Signifier]], [[IsLockFree1]], and [[IsLockFree2]] have been observed by any agent in the agent cluster they cannot change.
Note 2
The values of [[IsLockFree1]] and [[IsLockFree2]] are not necessarily determined by the hardware, but may also reflect 实现 choices that can vary over time and between ES implementations.
There is no [[IsLockFree4]] property: 4-byte atomic operations are always lock-free.
In practice, if an atomic operation is implemented with any type of lock the operation is not lock-free. Lock-free does not imply wait-free: there is no upper bound on how many machine steps may be required to complete a lock-free atomic operation.
That an atomic access of size n is lock-free does not imply anything about the (perceived) atomicity of non-atomic accesses of size n, specifically, non-atomic accesses may still be performed as a sequence of several separate memory accesses. See ReadSharedMemory and WriteSharedMemory for details.
Note 3
An agent is a specification mechanism and need not correspond to any particular artefact of an ES 实现.
8.7.1AgentSignifier( )
The 抽象操作 AgentSignifier takes no arguments. It 执行如下:
In some environments it may not be reasonable for a given agent to suspend. 例如, in a web browser environment, it may be reasonable to disallow suspending a document's main event handling thread, while still allowing workers' event handling threads to suspend.
上述限制的目的是为了避免因一个代理被停用而导致另一个代理死锁或饿死的现象。例如,如果一个在任何窗口中对文档有一个终生的依赖的 HTML 共享工人,被允许和这样一个依赖文档的敬业工人一起共享内存,当敬业的工人持有一个锁(例如,文档被推到窗口的历史中)时,文档和它的敬业的工人都将会被停用,并且如果之后共享的工人尝试去获取该锁,那么共享的工人将被锁直到敬业工人被再次激活。与此同时,其他试图从其他窗口访问共享工人的工人也将挨饿。
If p.[[GetPrototypeOf]] is not the 普通对象 内部方法 defined in 9.1.1, set done to true.
Else, set p to p.[[Prototype]].
Set O.[[Prototype]] to V.
Return true.
Note
The loop in step 8 guarantees that there will be no circularities in any prototype chain that only includes objects that use the 普通对象 definitions for [[GetPrototypeOf]] and [[SetPrototypeOf]].
9.1.3[[IsExtensible]] ( )
When the [[IsExtensible]] 内部方法 of O is called, 执行如下:
9.1.6.3ValidateAndApplyPropertyDescriptor ( O, P, extensible, Desc, current )
When the 抽象操作 ValidateAndApplyPropertyDescriptor is called with Object O, property key P, Boolean 值 extensible, and Property Descriptors Desc, and current, 执行如下:
Note
If undefined is passed as O, only validation is performed and no object updates are performed.
If O is not undefined, create an own 数据属性 named P of object O whose [[Value]], [[Writable]], [[Enumerable]] and [[Configurable]] 特性 values are described by Desc. If the value of an 特性 field of Desc is absent, the 特性 of the newly created property is set to its 默认值.
If O is not undefined, create an own 访问器属性 named P of object O whose [[Get]], [[Set]], [[Enumerable]] and [[Configurable]] 特性 values are described by Desc. If the value of an 特性 field of Desc is absent, the 特性 of the newly created property is set to its 默认值.
Return true.
If every field in Desc is absent, return true.
If current.[[Configurable]] is false, then
If Desc.[[Configurable]] is present and its value is true, return false.
If Desc.[[Enumerable]] is present and the [[Enumerable]] fields of current and Desc are the Boolean negation of each other, return false.
If O is not undefined, convert the property named P of object O from a 数据属性 to an 访问器属性. Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] 特性 and set the rest of the property's 特性 to their default values.
Else,
If O is not undefined, convert the property named P of object O from an 访问器属性 to a 数据属性. Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] 特性 and set the rest of the property's 特性 to their default values.
For each 自身属性 key P of O that is an 整数索引, in ascending numeric index order, do
Add P as the last element of keys.
For each 自身属性 key P of O that is a String but is not an 整数索引, in ascending chronological order of property creation, do
Add P as the last element of keys.
For each 自身属性 key P of O that is a Symbol, in ascending chronological order of property creation, do
Add P as the last element of keys.
Return keys.
9.1.12ObjectCreate ( proto [ , internalSlotsList ] )
The 抽象操作 ObjectCreate with argument proto (an object or null) is used to specify the runtime creation of new 普通对象. The 可选参数 internalSlotsList is a List of the names of additional 内部属性 that must be defined as part of the object. If the list is not provided, a new empty List is used. This 抽象操作 执行如下:
If internalSlotsList is not present, set internalSlotsList to a new empty List.
Let obj be a newly created object with an 内部属性 for each name in internalSlotsList.
Set obj's essential 内部方法 to the default 普通对象 definitions specified in 9.1.
The 抽象操作 OrdinaryCreateFromConstructor creates an 普通对象 whose [[Prototype]] value is retrieved from a 构造器's prototype property, if it exists. Otherwise the intrinsic named by intrinsicDefaultProto is used for [[Prototype]]. The optional internalSlotsList is a List of the names of additional 内部属性 that must be defined as part of the object. If the list is not provided, a new empty List is used. This 抽象操作 执行如下:
Assert: intrinsicDefaultProto is a String 值 that is this specification's name of an 内部对象. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] value of an object.
The 抽象操作 GetPrototypeFromConstructor determines the [[Prototype]] value that should be used to create an object corresponding to a specific 构造器. The value is retrieved from the 构造器's prototype property, if it exists. Otherwise the intrinsic named by intrinsicDefaultProto is used for [[Prototype]]. This 抽象操作 执行如下:
Assert: intrinsicDefaultProto is a String 值 that is this specification's name of an 内部对象. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] value of an object.
Set proto to realm's 内部对象 named intrinsicDefaultProto.
Return proto.
Note
If 构造器 does not supply a [[Prototype]] value, the 默认值 that is used is obtained from the realm of the 构造器 function rather than from the 运行时执行上下文.
9.2ES 函数对象
ES 函数对象 encapsulate parameterized ES 代码 closed over a 词法环境 and support the dynamic 估值 of that code. An ES 函数对象 is an 普通对象 and has the same 内部属性 and the same 内部方法 as other 普通对象. The code of an ES 函数对象 may be either 严格模式代码 (10.2.1) or non-strict code. An ES 函数对象 whose code is 严格模式代码 is called a strict function. One whose code is not 严格模式代码 is called a non-strict function.
ES 函数对象 have the additional 内部属性 listed in Table 27.
The script or module in which the function was created.
[[ThisMode]]
(lexical, strict, global)
Defines how this references are interpreted within the formal parameters and code body of the function. lexical means that this refers to the this value of a lexically enclosing function. strict means that the this value is used exactly as provided by an invocation of the function. global means that a this value of undefined is interpreted as a reference to the 全局对象.
When calleeContext is removed from the 执行上下文 堆栈 in step 8 it must not be destroyed if it is suspended and retained for later resumption by an accessible 生成器对象.
9.2.1.1PrepareForOrdinaryCall ( F, newTarget )
When the 抽象操作 PrepareForOrdinaryCall is called with 函数对象F and ES 语言值newTarget, 执行如下:
The 抽象操作 FunctionInitialize requires the arguments: a 函数对象F, kind which is one of (Normal, Method, Arrow), a parameter list 解析节点 specified by ParameterList, a body 解析节点 specified by Body, a 词法环境 specified by Scope. FunctionInitialize 执行如下:
Assert: F is an extensible object that does not have a length 自身属性.
Let len be the ExpectedArgumentCount of ParameterList.
The 抽象操作 FunctionCreate requires the arguments: kind which is one of (Normal, Method, Arrow), a parameter list 解析节点 specified by ParameterList, a body 解析节点 specified by Body, a 词法环境 specified by Scope, a Boolean flag Strict, and optionally, an object prototype. FunctionCreate 执行如下:
The 抽象操作 GeneratorFunctionCreate requires the arguments: kind which is one of (Normal, Method), a parameter list 解析节点 specified by ParameterList, a body 解析节点 specified by Body, a 词法环境 specified by Scope, and a Boolean flag Strict. GeneratorFunctionCreate 执行如下:
The 抽象操作 AsyncGeneratorFunctionCreate requires the arguments: kind which is one of (Normal, Method), a parameter list 解析节点 specified by ParameterList, a body 解析节点 specified by Body, a 词法环境 specified by Scope, and a Boolean flag Strict. AsyncGeneratorFunctionCreate 执行如下:
The 抽象操作 MakeConstructor requires a Function argument F and optionally, a Boolean writablePrototype and an object prototype. If prototype is provided it is assumed to already contain, if needed, a "构造器" property whose value is F. This operation converts F into a 构造器 by performing the following steps:
The 抽象操作 SetFunctionName requires a Function argument F, a String or Symbol argument name and optionally a String argument prefix. This operation adds a name property to F by performing the following steps:
Assert: F is an extensible object that does not have a name 自身属性.
When an 执行上下文 is established for evaluating an ES function a new 函数环境记录 is created and bindings for each formal parameter are instantiated in that 环境记录. Each declaration in the function body is also instantiated. If the function's formal parameters do not include any 默认值 初始化器 then the body declarations are instantiated in the same 环境记录 as the parameters. If 默认值 parameter 初始化器 exist, a second 环境记录 is created for the body declarations. Formal parameters and functions are initialized as part of FunctionDeclarationInstantiation. All other bindings are initialized during 估值 of the function body.
FunctionDeclarationInstantiation is performed as follows using arguments func and argumentsList. func is the 函数对象 for which the 执行上下文 is being established.
NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter, any parameter 默认值 初始化器, or any destructured parameters.
Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
Else,
Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
If hasParameterExpressions is false, then
NOTE: Only a single 词法环境 is needed for the parameters and top-level vars.
Let instantiatedVarNames be a copy of the ListparameterBindings.
For each n in varNames, do
If n is not an element of instantiatedVarNames, then
Append n to instantiatedVarNames.
Perform ! envRec.CreateMutableBinding(n, false).
Call envRec.InitializeBinding(n, undefined).
Let varEnv be env.
Let varEnvRec be envRec.
Else,
NOTE: A separate 环境记录 is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body.
NOTE: Non-strict functions use a separate lexical 环境记录 for top-level lexical declarations so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places all declarations into a new 环境记录.
Set the LexicalEnvironment of calleeContext to lexEnv.
Let lexDeclarations be the LexicallyScopedDeclarations of code.
For each element d in lexDeclarations, do
NOTE: A lexically declared name cannot be the same as a function/generator declaration, formal parameter, or a var name. Lexically declared names are only instantiated here but not initialized.
B.3.3 provides an extension to the above 算法 that is necessary for backwards compatibility with web browser implementations of ES that predate ES 2015.
Note 3
Parameter 初始化器s may contain direct eval expressions. Any top level declarations of such evals are only visible to the eval code (10.2). The creation of the environment for such declarations is described in 14.1.19.
9.3内置函数对象
The 内置函数对象 defined 在本规范中 may be implemented as either ES 函数对象 (9.2) whose behaviour is provided using ES 代码 or as 实现 provided function 外来对象 whose behaviour is provided in some other manner. In either case, the effect of calling such functions must conform to their specifications. An 实现 may also provide additional 内置函数对象 that are not defined 在本规范中.
If a 内置 函数对象 is implemented as an 外来对象 it must have the 普通对象 behaviour specified in 9.1. All such function 外来对象 also have [[Prototype]], [[Extensible]], [[Realm]], and [[ScriptOrModule]] 内部属性.
Unless otherwise specified every 内置 函数对象 has the %FunctionPrototype% object as the 初始值 of its [[Prototype]] 内部属性.
The behaviour specified for each 内置函数 via 算法步骤 or other means is the specification of the function body behaviour for both [[Call]] and [[Construct]] invocations of the function. However, [[Construct]] invocation is not supported by all 内置 functions. For each 内置函数, when invoked with [[Call]], the [[Call]] thisArgument provides the this value, the [[Call]] argumentsList provides the named parameters, and the NewTarget value is undefined. When invoked with [[Construct]], the this value is uninitialized, the [[Construct]] argumentsList provides the named parameters, and the [[Construct]] newTarget parameter provides the NewTarget value. If the 内置函数 is implemented as an ES 函数对象 then this specified behaviour must be implemented by the ES 代码 that is the body of the function. 内置 functions that are ES 函数对象 must be strict functions. If a 内置 构造器 has any [[Call]] behaviour other than throwing a TypeError 异常, an ES 实现 of the function must be done in a manner that does not cause the function's [[FunctionKind]] 内部属性 to have the value "classConstructor".
内置函数对象 that are not identified as constructors do not implement the [[Construct]] 内部方法 unless otherwise specified in the description of a particular function. When a 内置 构造器 is called as part of a new expression the argumentsList parameter of the invoked [[Construct]] 内部方法 provides the values for the 内置 构造器's named parameters.
内置 functions that are not constructors do not have a prototype property unless otherwise specified in the description of a particular function.
If a 内置 函数对象 is not implemented as an ES function it must provide [[Call]] and [[Construct]] 内部方法 that conform to the following definitions:
9.3.1[[Call]] ( thisArgument, argumentsList )
The [[Call]] 内部方法 for a 内置 函数对象F is called with parameters thisArgument and argumentsList, a List of ES 语言值. 执行如下:
Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
Perform any necessary 实现-defined initialization of calleeContext.
Push calleeContext onto the 执行上下文 堆栈; calleeContext is now the 运行时执行上下文.
Let result be the 完成记录 that is the result of evaluating F in an 实现-defined manner that conforms to the specification of F. thisArgument is the this value, argumentsList provides the named parameters, and the NewTarget value is undefined.
Remove calleeContext from the 执行上下文 堆栈 and restore callerContext as the 运行时执行上下文.
Return result.
Note
When calleeContext is removed from the 执行上下文 堆栈 it must not be destroyed if it has been suspended and retained by an accessible 生成器对象 for later resumption.
9.3.2[[Construct]] ( argumentsList, newTarget )
The [[Construct]] 内部方法 for 内置 函数对象F is called with parameters argumentsList and newTarget. The steps performed are the same as [[Call]] (see 9.3.1) except that step 10 is replaced by:
Let result be the 完成记录 that is the result of evaluating F in an 实现-defined manner that conforms to the specification of F. The this value is uninitialized, argumentsList provides the named parameters, and newTarget provides the NewTarget value.
The 抽象操作 CreateBuiltinFunction takes arguments steps, internalSlotsList, realm, and prototype. The argument internalSlotsList is a List of the names of additional 内部属性 that must be defined as part of the object. CreateBuiltinFunction returns a 内置 函数对象 created by the following steps:
Assert: steps is either a set of 算法步骤 or other definition of a function's behaviour provided 在本规范中.
If prototype is not present, set prototype to realm.[[Intrinsics]].[[%FunctionPrototype%]].
Let func be a new 内置 函数对象 that when called performs the action described by steps. The new 函数对象 has 内部属性 whose names are the elements of internalSlotsList. The 初始值 of each of those 内部属性 is undefined.
Set func.[[Realm]] to realm.
Set func.[[Prototype]] to prototype.
Set func.[[Extensible]] to true.
Set func.[[ScriptOrModule]] to null.
Return func.
Each 内置函数 defined 在本规范中 is created by calling the CreateBuiltinFunction 抽象操作.
9.4内置外来对象的内部方法和内部属性
This specification defines several kinds of 内置 外来对象. These objects generally behave similar to 普通对象 except for a few specific situations. The following 外来对象 use the 普通对象 内部方法 except where it is explicitly specified otherwise below:
9.4.1绑定函数外来对象
A bound function is an 外来对象 that wraps another 函数对象. A bound function is callable (it has a [[Call]] 内部方法 and may have a [[Construct]] 内部方法). Calling a bound function generally results in a call of its wrapped function.
Bound 函数对象 do not have the 内部属性 of ES 函数对象 defined in Table 27. Instead they have the 内部属性 defined in Table 28.
A list of values whose elements are used as the first arguments to any call to the wrapped function.
Bound 函数对象 provide all of the essential 内部方法 as specified in 9.1. However, they use the following definitions for the essential 内部方法 of 函数对象.
9.4.1.1[[Call]] ( thisArgument, argumentsList )
When the [[Call]] 内部方法 of a bound function外来对象, F, which was created using the bind function is called with parameters thisArgument and argumentsList, a List of ES 语言值, 执行如下:
Let target be F.[[BoundTargetFunction]].
Let boundThis be F.[[BoundThis]].
Let boundArgs be F.[[BoundArguments]].
Let args be a new list containing the same values as the list boundArgs in the same order followed by the same values as the list argumentsList in the same order.
When the [[Construct]] 内部方法 of a bound function外来对象, F that was created using the bind function is called with a list of arguments argumentsList and newTarget, 执行如下:
Let args be a new list containing the same values as the list boundArgs in the same order followed by the same values as the list argumentsList in the same order.
If SameValue(F, newTarget) is true, set newTarget to target.
Set obj.[[BoundTargetFunction]] to targetFunction.
Set obj.[[BoundThis]] to boundThis.
Set obj.[[BoundArguments]] to boundArgs.
Return obj.
9.4.2Array 外来对象
An Array object is an 外来对象 that gives special treatment to array index 属性键 (see 6.1.7). A property whose 属性名 is an array index is also called an element. Every Array object has a length property whose value is always 一个非负整数 less than 232. The value of the length property is numerically greater than the name of every 自身属性 whose name is an array index; whenever an 自身属性 of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever an 自身属性 is added whose name is an array index, the value of the length property is changed, if necessary, to be one more than the 数字值 of that array index; and whenever the value of the length property is changed, every 自身属性 whose name is an array index whose value is not smaller than the new length is deleted. This constraint applies only to 自身属性 of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
Array 外来对象 always have a non-configurable property named "length".
Array 外来对象 provide an alternative definition for the [[DefineOwnProperty]] 内部方法. Except for that 内部方法, Array 外来对象 provide all of the other essential 内部方法 as specified in 9.1.
9.4.2.1[[DefineOwnProperty]] ( P, Desc )
When the [[DefineOwnProperty]] 内部方法 of an Array 外来对象A is called with property key P, and 属性描述符Desc, 执行如下:
Assert: oldLenDesc will never be undefined or an accessor descriptor because Array 对象 are created with a length 数据属性 that cannot be deleted or reconfigured.
The 抽象操作 ArraySpeciesCreate with arguments originalArray and length is used to specify the creation of a new Array object using a 构造器 function that is derived from originalArray. It 执行如下:
If originalArray was created using the 标准内置 Array 构造器 for a realm that is not the realm of the 运行时执行上下文, then a new Array is created using the realm of the 运行时执行上下文. This maintains compatibility with Web browsers that have historically had that behaviour for the Array.prototype methods that now are defined using ArraySpeciesCreate.
9.4.2.4ArraySetLength ( A, Desc )
When the 抽象操作 ArraySetLength is called with an Array 外来对象A, and 属性描述符Desc, 执行如下:
Assert: oldLenDesc will never be undefined or an accessor descriptor because Array 对象 are created with a length 数据属性 that cannot be deleted or reconfigured.
Return OrdinaryDefineOwnProperty(A, "length", PropertyDescriptor{[[Writable]]: false}). This call will always return true.
Return true.
Note
In steps 3 and 4, if Desc.[[Value]] is an object then its valueOf method is called twice. This is legacy behaviour that was specified with this effect starting with the 2nd Edition of this specification.
9.4.3String 外来对象
A String 对象 is an 外来对象 that encapsulates a String 值 and exposes virtual integer-indexed data properties corresponding to the individual 代码单元 elements of the String 值. String 外来对象 always have a 数据属性 named "length" whose value is the number of 代码单元 elements in the encapsulated String 值. Both the 代码单元 data properties and the "length" property are non-writable and non-configurable.
String 外来对象 have the same 内部属性 as 普通对象. They also have a [[StringData]] 内部属性.
String 外来对象 provide alternative definitions for the following 内部方法. All of the other String 外来对象 essential 内部方法 that are not defined below are as specified in 9.1.
9.4.3.1[[GetOwnProperty]] ( P )
When the [[GetOwnProperty]] 内部方法 of a String 外来对象S is called with property key P, 执行如下:
Let resultStr be the String 值 of length 1, containing one 代码单元 from str, specifically the 代码单元 at index index.
Return a PropertyDescriptor{[[Value]]: resultStr, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false}.
9.4.4Arguments 外来对象
Most ES functions make an arguments object available to their code. Depending upon the characteristics of the function definition, its arguments object is either an 普通对象 or an arguments 外来对象. An arguments 外来对象 is an 外来对象 whose array index properties map to the formal parameters bindings of an invocation of its associated ES function.
Arguments 外来对象 have the same 内部属性 as 普通对象. They also have a [[ParameterMap]] 内部属性. Ordinary arguments objects also have a [[ParameterMap]] 内部属性 whose value is always undefined. For ordinary argument objects the [[ParameterMap]] 内部属性 is only used by Object.prototype.toString (19.1.3.6) to identify them as such.
Arguments 外来对象 provide alternative definitions for the following 内部方法. All of the other arguments 外来对象 essential 内部方法 that are not defined below are as specified in 9.1
Note 1
The integer-indexed data properties of an arguments 外来对象 whose numeric name values are less than the number of formal parameters of the corresponding 函数对象 initially share their values with the corresponding argument bindings in the function's 执行上下文. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an 访问器属性. If the arguments object is an 普通对象, the values of its properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.
Note 2
The ParameterMap object and its property values are used as a device for specifying the arguments object correspondence to argument bindings. The ParameterMap object and the objects that are the values of its properties are not directly observable from ES 代码. An ES 实现 does not need to actually create or use such objects to implement the specified 语义.
Note 3
Ordinary arguments objects define a non-configurable 访问器属性 named "callee" which throws a TypeError 异常 on access. The "callee" property has a more specific meaning for arguments 外来对象, which are created only for some class of non-strict functions. The definition of this property in the ordinary variant exists to ensure that it is not defined in any other manner by conforming ES implementations.
Note 4
ES implementations of arguments 外来对象 have historically contained an 访问器属性 named "caller". Prior to ES 2017, this specification included the definition of a throwing "caller" property on ordinary arguments objects. Since implementations do not contain this extension any longer, ES 2017 dropped the requirement for a throwing "caller" accessor.
9.4.4.1[[GetOwnProperty]] ( P )
The [[GetOwnProperty]] 内部方法 of an arguments 外来对象 when called with a property key P 执行如下:
An ArgSetter function is an anonymous 内置函数 with [[Name]] and [[Env]] 内部属性. When an ArgSetter function f is called with argument value it 执行如下:
Let name be f.[[Name]].
Let env be f.[[Env]].
Return env.SetMutableBinding(name, value, false).
Note
ArgSetter functions are never directly accessible to ES 代码.
9.4.5Integer-Indexed 外来对象
An Integer-Indexed 外来对象 is an 外来对象 that performs special handling of 整数索引 属性键.
Integer-Indexed 外来对象 have the same 内部属性 as 普通对象 and additionally [[ViewedArrayBuffer]], [[ArrayLength]], [[ByteOffset]], and [[TypedArrayName]] 内部属性.
Integer-Indexed 外来对象 provide alternative definitions for the following 内部方法. All of the other Integer-Indexed 外来对象 essential 内部方法 that are not defined below are as specified in 9.1.
9.4.5.1[[GetOwnProperty]] ( P )
When the [[GetOwnProperty]] 内部方法 of an Integer-Indexed 外来对象O is called with property key P, 执行如下:
The 抽象操作 IntegerIndexedObjectCreate with arguments prototype and internalSlotsList is used to specify the creation of new Integer-Indexed 外来对象. The argument internalSlotsList is a List of the names of additional 内部属性 that must be defined as part of the object. IntegerIndexedObjectCreate 执行如下:
Assert: internalSlotsList contains the names [[ViewedArrayBuffer]], [[ArrayLength]], [[ByteOffset]], and [[TypedArrayName]].
Let A be a newly created object with an 内部属性 for each name in internalSlotsList.
Set A's essential 内部方法 to the default 普通对象 definitions specified in 9.1.
A 模块命名空间对象 is an 外来对象 that exposes the bindings exported from an ES Module (See 15.2.3). There is a one-to-one correspondence between the String-keyed 自身属性 of a module 命名空间 外来对象 and the binding names exported by the Module. The exported bindings include any bindings that are indirectly exported using export * export items. Each String-valued 自身属性 key is the 字符值 of the corresponding exported binding name. These are the only String-keyed properties of a module 命名空间 外来对象. Each such property has the 特性 { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }. 模块命名空间对象 are not extensible.
A List containing the String values of the exported names exposed as 自身属性 of this object. The list is ordered as if an Array of those String values had been sorted using Array.prototype.sort using undefined as comparefn.
[[Prototype]]
Null
This slot always contains the value null (see 9.4.6.1).
Module 命名空间 外来对象 provide alternative definitions for all of the 内部方法 except [[GetPrototypeOf]], which behaves as defined in 9.1.1.
9.4.6.1[[SetPrototypeOf]] ( V )
When the [[SetPrototypeOf]] 内部方法 of a module 命名空间 外来对象O is called with argument V, 执行如下:
ResolveExport is idempotent and side-effect free. An 实现 might choose to pre-compute or cache the ResolveExport results for the [[Exports]] of each module 命名空间 外来对象.
9.4.6.8[[Set]] ( P, V, Receiver )
When the [[Set]] 内部方法 of a module 命名空间 外来对象O is called with property key P, value V, and ES 语言值Receiver, 执行如下:
Return false.
9.4.6.9[[Delete]] ( P )
When the [[Delete]] 内部方法 of a module 命名空间 外来对象O is called with property key P, 执行如下:
Set M's essential 内部方法 to the definitions specified in 9.4.6.
Set M.[[Module]] to module.
Let sortedExports be a new List containing the same values as the list exports where the values are ordered as if an Array of the same values had been sorted using Array.prototype.sort using undefined as comparefn.
Set M.[[Exports]] to sortedExports.
Create 自身属性 of M corresponding to the definitions in 26.3.
Set module.[[命名空间]] to M.
Return M.
9.4.7Immutable Prototype 外来对象
An immutable prototype 外来对象 is an 外来对象 that has a [[Prototype]] 内部属性 that will not change once it is initialized.
Immutable prototype 外来对象 have the same 内部属性 as 普通对象. They are exotic only in the following 内部方法. All other 内部方法 of immutable prototype 外来对象 that are not explicitly defined below are instead defined as in 普通对象.
9.4.7.1[[SetPrototypeOf]] ( V )
When the [[SetPrototypeOf]] 内部方法 of an immutable prototype 外来对象O is called with argument V, 执行如下:
A 代理对象 is an 外来对象 whose essential 内部方法 are partially implemented using ES 代码. Every Proxy 对象 has an 内部属性 called [[ProxyHandler]]. The value of [[ProxyHandler]] is an object, called the proxy's handler object, or null. Methods (see Table 30) of a handler object may be used to augment the 实现 for one or more of the 代理对象's 内部方法. Every 代理对象 also has an 内部属性 called [[ProxyTarget]] whose value is either an object or the null value. This object is called the proxy's target object.
Table 30: Proxy Handler Methods
内部方法
Handler Method
[[GetPrototypeOf]]
getPrototypeOf
[[SetPrototypeOf]]
setPrototypeOf
[[IsExtensible]]
isExtensible
[[PreventExtensions]]
preventExtensions
[[GetOwnProperty]]
getOwnPropertyDescriptor
[[DefineOwnProperty]]
defineProperty
[[HasProperty]]
has
[[Get]]
get
[[Set]]
set
[[Delete]]
deleteProperty
[[OwnPropertyKeys]]
ownKeys
[[Call]]
apply
[[Construct]]
construct
When a handler method is called to provide the 实现 of a 代理对象 内部方法, the handler method is passed the proxy's target object as a parameter. A proxy's handler object does not necessarily have a method corresponding to every essential 内部方法. Invoking an 内部方法 on the proxy results in the invocation of the corresponding 内部方法 on the proxy's target object if the handler object does not have a method corresponding to the internal trap.
The [[ProxyHandler]] and [[ProxyTarget]] 内部属性 of a 代理对象 are always initialized when the object is created and typically may not be modified. Some Proxy 对象 are created in a manner that permits them to be subsequently revoked. When a proxy is revoked, its [[ProxyHandler]] and [[ProxyTarget]] 内部属性 are set to null causing subsequent invocations of 内部方法 on that 代理对象 to 抛出一个 TypeError 异常.
Because Proxy 对象 permit the 实现 of 内部方法 to be provided by arbitrary ES 代码, it is possible to define a 代理对象 whose handler methods violates the 不变量 defined in 6.1.7.3. Some of the 内部方法 不变量 defined in 6.1.7.3 are essential integrity 不变量. These 不变量 are explicitly enforced by the 代理对象 内部方法 specified in this section. An ES 实现 must be robust in the presence of all possible invariant violations.
In the following 算法 descriptions, assume O is an ES 代理对象, P is a property key value, V is any ES 语言值 and Desc is a 属性描述符 record.
9.5.1[[GetPrototypeOf]] ( )
When the [[GetPrototypeOf]] 内部方法 of a Proxy 外来对象O is called, 执行如下:
If SameValue(handlerProto, targetProto) is false, 抛出一个 TypeError 异常.
Return handlerProto.
Note
[[GetPrototypeOf]] for Proxy 对象 enforces the following 不变量:
The result of [[GetPrototypeOf]] must be either an Object or null.
If the target object is not extensible, [[GetPrototypeOf]] applied to the 代理对象 must return the same value as [[GetPrototypeOf]] applied to the 代理对象's target object.
9.5.2[[SetPrototypeOf]] ( V )
When the [[SetPrototypeOf]] 内部方法 of a Proxy 外来对象O is called with argument V, 执行如下:
If targetDesc is undefined or targetDesc.[[Configurable]] is true, then
抛出一个 TypeError 异常.
Return resultDesc.
Note
[[GetOwnProperty]] for Proxy 对象 enforces the following 不变量:
The result of [[GetOwnProperty]] must be either an Object or undefined.
A property cannot be reported as non-existent, if it exists as a non-configurable 自身属性 of the target object.
A property cannot be reported as non-existent, if it exists as an 自身属性 of the target object and the target object is not extensible.
A property cannot be reported as existent, if it does not exist as an 自身属性 of the target object and the target object is not extensible.
A property cannot be reported as non-configurable, if it does not exist as an 自身属性 of the target object or if it exists as a configurable 自身属性 of the target object.
9.5.6[[DefineOwnProperty]] ( P, Desc )
When the [[DefineOwnProperty]] 内部方法 of a Proxy 外来对象O is called with property key P and 属性描述符Desc, 执行如下:
If settingConfigFalse is true and targetDesc.[[Configurable]] is true, 抛出一个 TypeError 异常.
Return true.
Note
[[DefineOwnProperty]] for Proxy 对象 enforces the following 不变量:
The result of [[DefineOwnProperty]] is a Boolean 值.
A property cannot be added, if the target object is not extensible.
A property cannot be non-configurable, unless there exists a corresponding non-configurable 自身属性 of the target object.
If a property has a corresponding target object property then applying the 属性描述符 of the property to the target object using [[DefineOwnProperty]] will not 抛出一个异常.
9.5.7[[HasProperty]] ( P )
When the [[HasProperty]] 内部方法 of a Proxy 外来对象O is called with property key P, 执行如下:
Let trapResult be ? Call(trap, handler, « target, P, Receiver »).
Let targetDesc be ? target.[[GetOwnProperty]](P).
If targetDesc is not undefined and targetDesc.[[Configurable]] is false, then
If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]] is false, then
If SameValue(trapResult, targetDesc.[[Value]]) is false, 抛出一个 TypeError 异常.
If IsAccessorDescriptor(targetDesc) is true and targetDesc.[[Get]] is undefined, then
If trapResult is not undefined, 抛出一个 TypeError 异常.
Return trapResult.
Note
[[Get]] for Proxy 对象 enforces the following 不变量:
The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own 数据属性.
The value reported for a property must be undefined if the corresponding target object property is a non-configurable own 访问器属性 that has undefined as its [[Get]] 特性.
9.5.9[[Set]] ( P, V, Receiver )
When the [[Set]] 内部方法 of a Proxy 外来对象O is called with property key P, value V, and ES 语言值Receiver, 执行如下:
If targetDesc.[[Set]] is undefined, 抛出一个 TypeError 异常.
Return true.
Note
[[Set]] for Proxy 对象 enforces the following 不变量:
The result of [[Set]] is a Boolean 值.
Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable own 数据属性.
Cannot set the value of a property if the corresponding target object property is a non-configurable own 访问器属性 that has undefined as its [[Set]] 特性.
9.5.10[[Delete]] ( P )
When the [[Delete]] 内部方法 of a Proxy 外来对象O is called with property key P, 执行如下:
ES 的代码是由 Unicode 编码的。ES 的源文本就是一串码点序列。范围在 U+0000 到 U+10FFFF 内的所有 Unicode 码点值,包括代理码点,都可能在被 ES 文法所认可的源文本中出现。被用来存储和交换 ES 源文本的实际的编码是和本规范无关的。抛开外部源文本编码不说,一个一致性的 ES 实现处理源文本就像是把它等价于 SourceCharacter 值的序列一样,每个 SourceCharacter 是一个 Unicode 码点。一致性的 ES 实现并不需要实现任何源文本的正规化,或是表现出它们是被正规化了一样。
Function code is generally provided as the bodies of 函数定义 (14.1), 箭头函数定义 (14.2), 方法定义 (14.3), 生成器函数定义 (14.4), 异步函数定义 (14.7), 异步生成器函数定义 (14.5), and Async Arrow Functions (14.8). Function code is also derived from the arguments to the Function构造器 (19.2.1.1), the GeneratorFunction构造器 (25.2.1.1), and the AsyncFunction构造器 (25.7.1.1).
10.2.1严格模式代码
一个 ES 脚本句法单元可以使用非严格或严格模式下的句法及语义进行处理。在一些情况中,代码会被作为严格模式代码来解释:
Function code that is supplied as the arguments to the 内置 Function, Generator, AsyncFunction, and AsyncGenerator constructors is 严格模式代码 if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
不是严格模式代码的 ES 代码叫做非严格代码。
10.2.2非 ES 函数
An ES 实现 may support the 估值 of function 外来对象 whose evaluative behaviour is expressed in some 实现-defined form of executable code other than via ES 代码. Whether a 函数对象 is an ES 代码 function or a non-ES function is not semantically observable from the perspective of an ES 代码 function that calls or is called by such a non-ES function.
11ES 语言: 词法
一个 ES 脚本或模块的源文本会先被转换为输入元素的一个序列,即 tokens、行终止符、评论、或空白。该源文本会被从左到右扫描,反复地将最长的可能码点序列作为下一个输入元素。
多个 lexical goals 的使用确保了没有词法上的歧义会影响到自动分号的插入。例如, there are no syntactic grammar contexts where both a leading division or division-assignment, and a leading RegularExpressionLiteral are permitted. 这是不会被分号插入影响到的(见 11.9);例如
a = b
/hi/g.exec(c).map(d);
where the first non-whitespace, non-comment 码点 after a LineTerminator is U+002F (SOLIDUS) and the syntactic context allows division or division-assignment, no semicolon is inserted at the LineTerminator. 即,上述例子会以下面的方式被解释;
The Unicode 格式控制字符 (i.e., the characters in category “Cf” in the Unicode Character Database 例如 LEFT-TO-RIGHT MARK or RIGHT-TO-LEFT MARK) are control codes used to control the formatting of a range of text in the absence of higher-level protocols for this (例如 mark-up languages).
It is useful to allow format-control characters in 源文本 to facilitate editing and display. All format control characters may be used within 评论, and within 字符型字面量, 模板字面量, and 正则表达式字面量.
U+200C (ZERO WIDTH NON-JOINER) and U+200D (ZERO WIDTH JOINER) are format-control characters that are used to make necessary distinctions when forming words or phrases in certain languages. In ES 源文本 these code points may also be used in an IdentifierName after the first character.
U+FEFF (ZERO WIDTH NO-BREAK SPACE) is a format-control character used primarily at the start of a text to mark it as Unicode and to allow detection of the text's encoding and byte order. <ZWNBSP> characters intended for this purpose can sometimes also appear after the start of a text, 例如 as a result of concatenating files. In ES 源文本 <ZWNBSP> code points are treated as 空白 characters (see 11.2).
The special treatment of certain format-control characters outside of 评论, 字符型字面量, and 正则表达式字面量 is summarized in Table 31.
The sets of code points with Unicode properties “ID_Start” and “ID_Continue” include, respectively, the code points with Unicode properties “Other_ID_Start” and “Other_ID_Continue”.
In some contexts yield and await are given the 语义 of an Identifier. See 12.1.1. In 严格模式代码, let and static are treated as 保留字 through static semantic restrictions (see 12.1.1, 13.3.1.1, 13.7.5.1, and 14.6.1) rather than the 词法.
正则表达式字面量 may not be empty; instead of representing an empty 正则表达式 literal, the 代码单元 sequence // starts a single-line comment. To specify an empty 正则表达式, use: /(?:)/.正则表达式字面量不能为空;并不是说正则表达式字面量不能代表空,码点序列 // 会启动一个单行注释。要指定一个空正则表达式,使用:/(?:)/。
The TRV of NotEscapeSequence::xHexDigit[lookahead ∉ HexDigit] is the sequence consisting of the 代码单元 0x0078 (LATIN SMALL LETTER X) followed by the 代码单元 of the TRV of HexDigit.
The TRV of NotEscapeSequence::u[lookahead ∉ HexDigit][lookahead ≠ {] is the 代码单元 0x0075 (LATIN SMALL LETTER U).
The TRV of NotEscapeSequence::uHexDigit[lookahead ∉ HexDigit] is the sequence consisting of the 代码单元 0x0075 (LATIN SMALL LETTER U) followed by the 代码单元 of the TRV of HexDigit.
The TRV of NotEscapeSequence::uHexDigitHexDigit[lookahead ∉ HexDigit] is the sequence consisting of the 代码单元 0x0075 (LATIN SMALL LETTER U) followed by the 代码单元 of the TRV of the first HexDigit followed by the 代码单元 of the TRV of the second HexDigit.
The TRV of NotEscapeSequence::uHexDigitHexDigitHexDigit[lookahead ∉ HexDigit] is the sequence consisting of the 代码单元 0x0075 (LATIN SMALL LETTER U) followed by the 代码单元 of the TRV of the first HexDigit followed by the 代码单元 of the TRV of the second HexDigit followed by the 代码单元 of the TRV of the third HexDigit.
The TRV of NotEscapeSequence::u{[lookahead ∉ HexDigit] is the sequence consisting of the 代码单元 0x0075 (LATIN SMALL LETTER U) followed by the 代码单元 0x007B (LEFT CURLY BRACKET).
The TRV of NotEscapeSequence::u{NotCodePoint[lookahead ∉ HexDigit] is the sequence consisting of the 代码单元 0x0075 (LATIN SMALL LETTER U) followed by the 代码单元 0x007B (LEFT CURLY BRACKET) followed by the 代码单元 of the TRV of NotCodePoint.
The TRV of NotEscapeSequence::u{CodePoint[lookahead ∉ HexDigit][lookahead ≠ }] is the sequence consisting of the 代码单元 0x0075 (LATIN SMALL LETTER U) followed by the 代码单元 0x007B (LEFT CURLY BRACKET) followed by the 代码单元 of the TRV of CodePoint.
The TRV of HexEscapeSequence::xHexDigitHexDigit is the sequence consisting of the 代码单元 0x0078 (LATIN SMALL LETTER X) followed by TRV of the first HexDigit followed by the TRV of the second HexDigit.
The TRV of UnicodeEscapeSequence::u{CodePoint} is the sequence consisting of the 代码单元 0x0075 (LATIN SMALL LETTER U) followed by the 代码单元 0x007B (LEFT CURLY BRACKET) followed by TRV of CodePoint followed by the 代码单元 0x007D (RIGHT CURLY BRACKET).
The TRV of LineTerminatorSequence::<CR><LF> is the sequence consisting of the 代码单元 0x000A (LINE FEED).
Note
TV excludes the 代码单元 of LineContinuation while TRV includes them. <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV. An explicit EscapeSequence is needed to include a <CR> or <CR><LF> sequence.
11.9自动分号插入
大多数 ES 语句必须用一个分号终止。这些分号总是明确的显示在源文本里。然而,为了方便起见,某些情况下这些分号可以在源文本里省略。即这些情况下,分号会被自动插入到源代码的 token 流中。
When, as the 源文本 is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation “[no LineTerminator here]” within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.
然而,上述规则有一个附加的优先条件:如果插入分号后解析结果是空语句,或插入分号后它成为 for 语句头部的两个分号之一(见 13.7.4),那么将不会自动插入分号。
Note
The following are the only restricted productions in the grammar:
这是一个句法错误如果 this phrase is contained in 严格模式代码 and the 字符值 of IdentifierName is: "implements", "interface", "let", "package", "private", "protected", "public", "static", or "yield".
undefined is passed for environment to indicate that a PutValue operation should be used to assign the initialization value. This is the case for var statements and formal parameter lists of some non-strict functions (See 9.2.13). In those cases a lexical binding is hoisted and preinitialized prior to 估值 of its 初始化器.
In non-strict code, the keyword yield may be used as an identifier. Evaluating the IdentifierReference resolves the binding of yield as if it was an Identifier. 早期错误 restriction ensures that such an 估值 only can occur for non-strict code.
Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.数组元素可能在元素列表的开始、结束,或者中间位置被省略。每当元素列表中的一个逗号不在 AssignmentExpression 之前(如,一个逗号在另一个逗号之前)时,缺失的数组元素会对数组长度有贡献,并且增加后续元素的索引值。被省略的数组元素是没有定义的。如果一个元素在数组末尾被省略,那么该元素不会对数组的长度有贡献。
CreateDataProperty is used to ensure that 自身属性 are defined for the array even if the 标准内置 Array 原型对象 has been modified in a manner that would preclude the creation of new 自身属性 using [[Set]].
In certain contexts, ObjectLiteral is used as a cover grammar for a more restricted secondary grammar. The CoverInitializedName production is necessary to fully cover these secondary grammars. However, use of this production results in an early Syntax Error in normal contexts where an actual ObjectLiteral is expected.
这是一个句法错误如果 FlagText of RegularExpressionLiteral contains any code points other than "g", "i", "m", "u", or "y", or if it contains the same 码点 more than once.
Return a List whose first element is siteObj, whose second elements is firstSub, and whose subsequent elements are the elements of restSub, in order. restSub may contain no elements.
Append the Record{[[Site]]: templateLiteral, [[Array]]: template} to templateRegistry.
Return template.
Note 1
The creation of a template object cannot result in an abrupt completion.
Note 2
Each TemplateLiteral in the program code of a realm is associated with a unique template object that is used in the 估值 of 标签模板 (12.2.9.6). The template objects are frozen and the same template object is used each time a specific tagged Template is evaluated. Whether template objects are created lazily upon first 估值 of the TemplateLiteral or eagerly prior to first 估值 is an 实现 choice that is not observable to ES 代码.
Note 3
Future editions of this specification may define additional non-enumerable properties of template objects.
This 算法 does not apply GetValue to the result of evaluating Expression. The principal motivation for this is so that operators 例如 delete and typeof may be applied to parenthesized expressions.
Let propertyKey be ? ToPropertyKey(propertyNameValue).
If the code matched by this MemberExpression is 严格模式代码, let strict be true, else let strict be false.
Return a value of type Reference whose base value component is bv, whose referenced name component is propertyKey, and whose strict reference flag is strict.
If the code matched by this MemberExpression is 严格模式代码, let strict be true, else let strict be false.
Return a value of type Reference whose base value component is bv, whose referenced name component is propertyNameString, and whose strict reference flag is strict.
Return a value of type Reference that is a Super 引用 whose base value component is bv, whose referenced name component is propertyKey, whose thisValue component is actualThis, and whose strict reference flag is strict.
12.3.6参数列表
Note
The 估值 of an argument list produces a List of values.
Append nextArg as the last element of precedingArgs.
12.3.7标签模板
Note
A tagged template is a function call where the arguments of the call are derived from a TemplateLiteral (12.2.9). The actual arguments include a template object (12.2.9.4) and the values produced by evaluating the expressions embedded within the TemplateLiteral.
When a delete 运算符 occurs within 严格模式代码, a SyntaxError 异常 is thrown if its UnaryExpression is a direct reference to a variable, function argument, or function name. In addition, if a delete 运算符 occurs within 严格模式代码 and the property to be deleted has the 特性 { [[Configurable]]: false }, a TypeError 异常 is thrown.
Returns an 实现-dependent approximation of the result of raising base to the power exponent.
If exponent is NaN, the result is NaN.
If exponent is +0, the result is 1, even if base is NaN.
If exponent is -0, the result is 1, even if base is NaN.
If base is NaN and exponent is nonzero, the result is NaN.
If abs(base) > 1 and exponent is +∞, the result is +∞.
If abs(base) > 1 and exponent is -∞, the result is +0.
If abs(base) is 1 and exponent is +∞, the result is NaN.
If abs(base) is 1 and exponent is -∞, the result is NaN.
If abs(base) < 1 and exponent is +∞, the result is +0.
If abs(base) < 1 and exponent is -∞, the result is +∞.
If base is +∞ and exponent > 0, the result is +∞.
If base is +∞ and exponent < 0, the result is +0.
If base is -∞ and exponent > 0 and exponent is an odd integer, the result is -∞.
If base is -∞ and exponent > 0 and exponent is not an odd integer, the result is +∞.
If base is -∞ and exponent < 0 and exponent is an odd integer, the result is -0.
If base is -∞ and exponent < 0 and exponent is not an odd integer, the result is +0.
If base is +0 and exponent > 0, the result is +0.
If base is +0 and exponent < 0, the result is +∞.
If base is -0 and exponent > 0 and exponent is an odd integer, the result is -0.
If base is -0 and exponent > 0 and exponent is not an odd integer, the result is +0.
If base is -0 and exponent < 0 and exponent is an odd integer, the result is -∞.
If base is -0 and exponent < 0 and exponent is not an odd integer, the result is +∞.
If base < 0 and base is finite and exponent is finite and exponent is not an integer, the result is NaN.
Note
The result of base**exponent when base is 1 or -1 and exponent is +Infinity or -Infinity differs from IEEE 754-2008. The first edition of ES specified a result of NaN for this operation, whereas later versions of IEEE 754-2008 specified 1. The historical ES behaviour is preserved for compatibility reasons.
The *MultiplicativeOperator performs multiplication, producing the product of its operands. Multiplication is commutative. Multiplication is not always associative in ES, because of finite precision.
The result of a floating-point multiplication is governed by the rules of IEEE 754-2008 binary double-precision arithmetic:
If either operand is NaN, the result is NaN.
The sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
Multiplication of an infinity by a zero results in NaN.
Multiplication of an infinity by an infinity results in an infinity. The sign is determined by the rule already stated above.
Multiplication of an infinity by a finite nonzero value results in a signed infinity. The sign is determined by the rule already stated above.
In the remaining cases, where neither an infinity nor NaN is involved, the product is computed and rounded to the nearest representable value using IEEE 754-2008 round to nearest, ties to even mode. If the magnitude is too large to represent, the result is then an infinity of appropriate sign. If the magnitude is too small to represent, the result is then a zero of appropriate sign. The ES language requires support of gradual underflow as defined by IEEE 754-2008.
12.7.3.2Applying the / 运算符
The /MultiplicativeOperator performs division, producing the quotient of its operands. The left operand is the dividend and the right operand is the divisor. ES does not perform integer division. The operands and result of all division operations are double-precision floating-point numbers. The result of division is determined by the specification of IEEE 754-2008 arithmetic:
If either operand is NaN, the result is NaN.
The sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
Division of an infinity by an infinity results in NaN.
Division of an infinity by a zero results in an infinity. The sign is determined by the rule already stated above.
Division of an infinity by a nonzero finite value results in a signed infinity. The sign is determined by the rule already stated above.
Division of a finite value by an infinity results in zero. The sign is determined by the rule already stated above.
Division of a zero by a zero results in NaN; division of zero by any other finite value results in zero, with the sign determined by the rule already stated above.
Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule already stated above.
In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the quotient is computed and rounded to the nearest representable value using IEEE 754-2008 round to nearest, ties to even mode. If the magnitude is too large to represent, the operation overflows; the result is then an infinity of appropriate sign. If the magnitude is too small to represent, the operation underflows and the result is a zero of the appropriate sign. The ES language requires support of gradual underflow as defined by IEEE 754-2008.
12.7.3.3Applying the % 运算符
The %MultiplicativeOperator yields the remainder of its operands from an implied division; the left operand is the dividend and the right operand is the divisor.
Note
In C and C++, the remainder 运算符 accepts only integral operands; in ES, it also accepts floating-point operands.
The result of a floating-point remainder operation as computed by the % 运算符 is not the same as the “remainder” operation defined by IEEE 754-2008. The IEEE 754-2008 “remainder” operation computes the remainder from a rounding division, not a truncating division, and so its behaviour is not analogous to that of the usual integer remainder 运算符. Instead the ES language defines % on floating-point operations to behave in a manner analogous to that of the Java integer remainder 运算符; this may be compared with the C library function fmod.
The result of an ES floating-point remainder operation is determined by the rules of IEEE arithmetic:
If either operand is NaN, the result is NaN.
The sign of the result equals the sign of the dividend.
If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
If the dividend is finite and the divisor is an infinity, the result equals the dividend.
If the dividend is a zero and the divisor is nonzero and finite, the result is the same as the dividend.
In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n - (d × q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d. r is computed and rounded to the nearest representable value using IEEE 754-2008 round to nearest, ties to even mode.
Return the result of applying the addition operation to lnum and rnum. See the Note below 12.8.5.
Note 1
No hint is provided in the calls to ToPrimitive in steps 5 and 6. All standard objects except 日期对象 handle the absence of a hint as if the hint Number were given; 日期对象 handle the absence of a hint as if the hint String were given. 外来对象 may handle the absence of a hint in some other manner.
Note 2
Step 7 differs from step 3 of the 抽象关系比较 算法, by using the 逻辑或运算 instead of the 逻辑与运算.
Return the result of applying the subtraction operation to lnum and rnum. See the note below 12.8.5.
12.8.5对数字应用加法运算符
The + 运算符 performs addition when applied to two operands of numeric type, producing the sum of the operands. The - 运算符 performs subtraction, producing the difference of two numeric operands.
Addition is a commutative operation, but not always associative.
The result of an addition is determined using the rules of IEEE 754-2008 binary double-precision arithmetic:
If either operand is NaN, the result is NaN.
The sum of two infinities of opposite sign is NaN.
The sum of two infinities of the same sign is the infinity of that sign.
The sum of an infinity and a finite value is equal to the infinite operand.
The sum of two negative zeroes is -0. The sum of two positive zeroes, or of two zeroes of opposite sign, is +0.
The sum of a zero and a nonzero finite value is equal to the nonzero operand.
The sum of two nonzero finite values of the same magnitude and opposite sign is +0.
In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, and the operands have the same sign or have different magnitudes, the sum is computed and rounded to the nearest representable value using IEEE 754-2008 round to nearest, ties to even mode. If the magnitude is too large to represent, the operation overflows and the result is then an infinity of appropriate sign. The ES language requires support of gradual underflow as defined by IEEE 754-2008.
Note
The - 运算符 performs subtraction when applied to two operands of numeric type, producing the difference of its operands; the left operand is the minuend and the right operand is the subtrahend. Given numeric operands a and b, it is always the case that a-b produces the same result as a+(-b).
Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.
Return the result of performing a sign-extending right shift of lnum by shiftCount bits. The most significant bit is propagated. The result is a signed 32-bit integer.
12.9.5无符号右移运算符 ( >>> )
Note
Performs a zero-filling bitwise right shift operation on the left operand by the amount specified by the right operand.
Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.
Return the result of performing a zero-filling right shift of lnum by shiftCount bits. Vacated bits are filled with zero. The result is an unsigned 32-bit integer.
12.10关系运算符
Note 1
The result of evaluating a relational 运算符 is always of type Boolean, reflecting whether the relationship named by the 运算符 holds between its two operands.
The 抽象操作 InstanceofOperator(V, target) implements the generic 算法 for determining if ES 值 V is an instance of object target either by consulting target's @@hasinstance method or, if absent, determining whether the value of target's prototype property is present in V's prototype chain. This 抽象操作 执行如下:
Steps 4 and 5 provide compatibility with previous editions of ES that did not use a @@hasInstance method to define the instanceof 运算符 语义. If an object does not define or inherit @@hasInstance it uses the default instanceof 语义.
12.11相等运算符
Note
The result of evaluating an equality 运算符 is always of type Boolean, reflecting whether the relationship named by the 运算符 holds between its two operands.
Let r be the result of performing 严格相等比较rval === lval.
If r is true, return false. Otherwise, return true.
Note 1
Given the above definition of equality:
String comparison can be forced by: "" + a == "" + b.
Numeric comparison can be forced by: +a == +b.
Boolean comparison can be forced by: !a == !b.
Note 2
The 相等运算符 maintain the following 不变量:
A != B is equivalent to !(A == B).
A == B is equivalent to B == A, except in the order of 估值 of A and B.
Note 3
The equality 运算符 is not always transitive. 例如, there might be two distinct 字符串对象, each representing the same String 值; each String 对象 would be considered equal to the String 值 by the == 运算符, but the two 字符串对象 would not be equal to each other. 例如:
new String("a") == "a" and "a" == new String("a") are both true.
new String("a") == new String("a") is false.
Note 4
Comparison of Strings uses a simple equality test on sequences of 代码单元 values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the Unicode specification. Therefore Strings values that are canonically equal according to the Unicode standard could test as unequal. In effect this 算法 assumes that both Strings are already in normalized form.
The value produced by a && or || 运算符 is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
The grammar for a ConditionalExpression in ES is slightly different from that in C and Java, which each allow the second subexpression to be an Expression but restrict the third expression to be a ConditionalExpression. The motivation for this difference in ES is to allow an assignment expression to be governed by either arm of a conditional and to eliminate the confusing and fairly useless case of a comma expression as the centre expression.
When an assignment occurs within 严格模式代码, it is a runtime error if lref in step 1.f of the first 算法 or step 7 of the second 算法 it is an unresolvable reference. If it is, a ReferenceError 异常 is thrown. The LeftHandSideExpression also may not be a reference to a 数据属性 with the 特性 value {[[Writable]]: false}, to an 访问器属性 with the 特性 value {[[Set]]: undefined}, nor to a non-existent property of an object for which the IsExtensible predicate returns the value false. In these cases a TypeError 异常 is thrown.
Left to right 估值 order is maintained by evaluating a DestructuringAssignmentTarget that is not a destructuring pattern prior to accessing the 迭代器 or evaluating the 初始化器.
The value of a StatementList is the value of the last value-producing item in the StatementList. 例如, the following calls to the eval function all return the value 1:
When a Block or CaseBlock is evaluated a new declarative 环境记录 is created and bindings for each block scoped variable, constant, function, or class declared in the block are instantiated in the 环境记录.
BlockDeclarationInstantiation is performed as follows using arguments code and env. code is the 解析节点 corresponding to the body of the block. env is the 词法环境 in which bindings are to be created.
Let fo be the result of performing InstantiateFunctionObject for d with argument env.
Perform envRec.InitializeBinding(fn, fo).
13.3声明和变量语句
13.3.1Let 和 Const 声明
Note
let and const declarations define variables that are scoped to the 运行时执行上下文's LexicalEnvironment. The variables are created when their containing 词法环境 is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated. A variable defined by a LexicalBinding with an 初始化器 is assigned the value of its 初始化器's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an 初始化器 the variable is assigned the value undefined when the LexicalBinding is evaluated.
Return the result of performing 绑定初始化 for BindingPattern using value and env as the arguments.
13.3.2变量语句
Note
A var statement declares variables that are scoped to the 运行时执行上下文's VariableEnvironment. Var variables are created when their containing 词法环境 is instantiated and are initialized to undefined when created. Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collectively define only one variable. A variable defined by a VariableDeclaration with an 初始化器 is assigned the value of its 初始化器's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.
If a VariableDeclaration is nested within a with statement and the BindingIdentifier in the VariableDeclaration is the same as a 属性名 of the binding object of the with statement's object 环境记录, then step 6 will assign value to the property instead of assigning to the VariableEnvironment binding of the Identifier.
When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialization value. This is the case for formal parameter lists of non-strict functions. In that case the formal parameter bindings are preinitialized in order to deal with the possibility of multiple parameters with the same name.
When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialization value. This is the case for formal parameter lists of non-strict functions. In that case the formal parameter bindings are preinitialized in order to deal with the possibility of multiple parameters with the same name.
With parameters value, environment, and propertyName.
Note
When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialization value. This is the case for formal parameter lists of non-strict functions. In that case the formal parameter bindings are preinitialized in order to deal with the possibility of multiple parameters with the same name.
Each else for which the choice of associated if is ambiguous shall be associated with the nearest possible if that would otherwise have no corresponding else.
undefined is passed for environment to indicate that a PutValue operation should be used to assign the initialization value. This is the case for var statements and the formal parameter lists of some non-strict functions (see 9.2.13). In those cases a lexical binding is hoisted and preinitialized prior to 估值 of its 初始化器.
The 抽象操作 ForIn/OfHeadEvaluation is called with arguments TDZnames, expr, and iterationKind. The value of iterationKind is either enumerate, iterate, or async-iterate.
The 抽象操作 ForIn/OfBodyEvaluation is called with arguments lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet, and 可选参数 iteratorKind. The value of lhsKind is either assignment, varBinding or lexicalBinding. The value of iteratorKind is either sync or async.
If iteratorKind is not present, set iteratorKind to sync.
Return an 迭代器 object (25.1.1.2) whose next method iterates over all the String-valued keys of enumerable properties of O. The 迭代器 object is never directly accessible to ES 代码. The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.
The 迭代器's throw and return methods are null and are never invoked. The 迭代器's next method processes object properties to determine whether the property key should be returned as an 迭代器 value. Returned 属性键 do not include keys that are Symbols. Properties of the target object may be deleted during enumeration. A property that is deleted before it is processed by the 迭代器's next method is ignored. If new properties are added to the target object during enumeration, the newly added properties are not guaranteed to be processed in the active enumeration. A 属性名 will be returned by the 迭代器's next method at most once in any enumeration.
Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively; but a property of a prototype is not processed if it has the same name as a property that has already been processed by the 迭代器's next method. The values of [[Enumerable]] 特性 are not considered when determining if a property of a 原型对象 has already been processed. The enumerable property names of prototype objects must be obtained by invoking EnumerateObjectProperties passing the 原型对象 as the argument. EnumerateObjectProperties must obtain the 自身属性 keys of the target object by calling its [[OwnPropertyKeys]] 内部方法. 属性特性 of the target object must be obtained by calling its [[GetOwnProperty]] 内部方法.
Note
The following is an informative definition of an ES 生成器函数 that conforms to these rules:
function* EnumerateObjectProperties(obj) {
const visited = newSet();
for (const key ofReflect.ownKeys(obj)) {
if (typeof key === "symbol") continue;
const desc = Reflect.getOwnPropertyDescriptor(obj, key);
if (desc) {
visited.add(key);
if (desc.enumerable) yield key;
}
}
const proto = Reflect.getPrototypeOf(obj);
if (proto === null) return;
for (const protoKey of EnumerateObjectProperties(proto)) {
if (!visited.has(protoKey)) yield protoKey;
}
}
A return statement causes a function to cease execution and, in most cases, returns a value to the caller. If Expression is omitted, the 返回值 is undefined. Otherwise, the 返回值 is the value of Expression. A return statement may not actually return a value to the caller depending on surrounding context. 例如, in a try block, a return statement's 完成记录 may be replaced with another 完成记录 during 估值 of the finally block.
with 语句 adds an object 环境记录 for a computed object to the 词法环境 of the 运行时执行上下文. It then executes a statement using this augmented 词法环境. Finally, it restores the original 词法环境.
No matter how control leaves the embedded Statement, whether normally or by some form of abrupt completion or 异常, the LexicalEnvironment is always restored to its former state.
A Statement may be prefixed by a label. 标签语句 are only used in conjunction with labelled break and continue statements. ES has no goto statement. A Statement can be part of a LabelledStatement, which itself can be part of a LabelledStatement, and so on. The labels introduced this way are collectively referred to as the “current label set” when describing the 语义 of individual statements.
try 语句 encloses a block of code in which an exceptional condition can occur, 例如 a runtime error or a throw statement. The catch clause provides the 异常-handling code. When a catch clause catches an 异常, its CatchParameter is bound to that 异常.
Evaluating a DebuggerStatement may allow an 实现 to cause a breakpoint when run under a debugger. If a debugger is not present or active this statement has no observable effect.
Multiple occurrences of the same BindingIdentifier in a FormalParameterList is only allowed for functions which have simple parameter lists and which are not defined in 严格模式代码.
The ExpectedArgumentCount of a FormalParameterList is the number of FormalParameters to the left of either the rest parameter or the first FormalParameter with an 初始化器. A FormalParameter without an 初始化器 is allowed after the first parameter with an 初始化器 but such parameters are considered to be optional with undefined as their 默认值.
The 抽象操作 IsAnonymousFunctionDefinition determines if its argument is a function definition that does not bind a name. The argument expr is the result of parsing an AssignmentExpression or 初始化器. 执行如下:
When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialization value. This is the case for formal parameter lists of non-strict functions. In that case the formal parameter bindings are preinitialized in order to deal with the possibility of multiple parameters with the same name.
If ContainsExpression of BindingElement is false, return the result of performing IteratorBindingInitialization for BindingElement using iteratorRecord and environment as the arguments.
If ContainsExpression of BindingRestElement is false, return the result of performing IteratorBindingInitialization for BindingRestElement using iteratorRecord and environment as the arguments.
A prototype property is automatically created for every function defined using a FunctionDeclaration or FunctionExpression, to allow for the possibility that the function will be used as a 构造器.
Normally, Contains does not look inside most function forms. However, Contains is used to detect new.target, this, and super usage within an ArrowFunction.
When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialization value. This is the case for formal parameter lists of non-strict functions. In that case the formal parameter bindings are preinitialized in order to deal with the possibility of multiple parameters with the same name.
An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function. Even though an ArrowFunction may contain references to super, the 函数对象 created in step 4 is not made into a method by performing MakeMethod. An ArrowFunction that references super is always contained within a non-ArrowFunction and the necessary state to implement super is accessible via the scope that is captured by the 函数对象 of the ArrowFunction.
YieldExpression cannot be used within the FormalParameters of a 生成器函数 because any expressions that are part of FormalParameters are evaluated before the resulting 生成器对象 is in a resumable state.
Let innerResult be ? Call(throw, 迭代器, « received.[[Value]] »).
If generatorKind is async, then set innerResult to ? Await(innerResult).
NOTE: Exceptions from the inner 迭代器 throw method are propagated. Normal completions from an inner throw method are processed similarly to an inner next.
If Type(innerResult) is not Object, 抛出一个 TypeError 异常.
Set the 运行时执行上下文's LexicalEnvironment to classScope.
Let constructorInfo be the result of performing DefineMethod for 构造器 with arguments proto and constructorParent as the optional functionPrototype argument.
Return the result of ClassDefinitionEvaluation of ClassTail with argument undefined.
Note
ClassDeclaration:classClassTail only occurs as part of an ExportDeclaration and the setting of a name property and establishing its binding are handled as part of the 估值 action for that production. See 15.2.3.11.
When Module is the syntactic 目标符 and the [Await] parameter is absent, await is parsed as a keyword and will be a Syntax error. When Script is the syntactic 目标符, await may be parsed as an identifier when the [Await] parameter is absent. This includes the following contexts:
If the source code matching this production is strict code, 这是一个句法错误如果 BindingIdentifier is present and the 字符值 of BindingIdentifier is "eval" or "arguments".
Normally, Contains does not look inside most function forms. However, Contains is used to detect new.target, this, and super usage within an AsyncArrowFunction.
Return the result of HasCallInTailPosition of body with argument call.
Note
尾调用 are only defined in 严格模式代码 because of a common non-standard language extension (see 9.2.8) that enables observation of the chain of caller contexts.
14.9.2静态语义: HasCallInTailPosition
With parameter call.
Note
call is a 解析节点 that represents a specific range of 源文本. When the following 算法 compare call to another 解析节点, it is a test of whether they represent the same 源文本.
Return HasCallInTailPosition of Block with argument call.
14.9.2.2Expression Rules
Note
A potential tail position call that is immediately followed by return GetValue of the call result is also a possible tail position call. 函数调用 cannot return reference values, so such a GetValue operation will always return the same value as the actual function call result.
Pop leafContext from the 执行上下文 堆栈. The 执行上下文 now on the top of the stack becomes the 运行时执行上下文.
Assert: leafContext has no further use. It will never be activated as the 运行时执行上下文.
A tail position call must either release any transient internal resources associated with the currently executing function 执行上下文 before invoking the target function or reuse those resources in support of the target function.
Note
例如, a tail position call should only grow an 实现's activation record stack by the amount that the size of the target function's activation record exceeds the size of the calling function's activation record. If the target function's activation record is smaller, then the total size of the stack should decrease.
这是一个句法错误如果 StatementList Contains super unless the source code containing super is eval code that is being processed by a direct eval. Additional 早期错误 rules for super within direct eval are defined in 18.2.1.1.
Parse 源文本 using Script as the 目标符 and analyse the parse result for any 早期错误 conditions. If the parse was successful and no 早期错误 were found, let body be the resulting parse tree. Otherwise, let body be a List of one or more SyntaxError or ReferenceError objects representing the parsing errors and/or 早期错误. Parsing and 早期错误 detection may be interweaved in an 实现-dependent manner. If more than one 解析错误 or 早期错误 is present, the number and ordering of 错误对象 in the list is 实现-dependent, but at least one must be present.
An 实现 may parse script 源文本 and analyse it for 早期错误 conditions prior to 估值 of ParseScript for that script 源文本. However, the reporting of any errors must be deferred until the point where this specification actually performs ParseScript upon that 源文本.
15.1.10ScriptEvaluation ( scriptRecord )
Let globalEnv be scriptRecord.[[Realm]].[[GlobalEnv]].
When an 执行上下文 is established for evaluating 脚本, declarations are instantiated in the current 全局环境. Each global binding declared in the code is instantiated.
GlobalDeclarationInstantiation is performed as follows using arguments script and env. script is the ScriptBody for which the 执行上下文 is being established. env is the global 词法环境 in which bindings are to be created.
If vn is not an element of declaredFunctionNames, then
Let vnDefinable be ? envRec.CanDeclareGlobalVar(vn).
If vnDefinable is false, 抛出一个 TypeError 异常.
If vn is not an element of declaredVarNames, then
Append vn to declaredVarNames.
NOTE: No abnormal terminations occur after this 算法步骤 if the 全局对象 is an 普通对象. However, if the 全局对象 is a Proxy 外来对象 it may exhibit behaviours that cause abnormal terminations in some of the following steps.
NOTE: Annex B.3.3.2 adds additional steps at this point.
Let lexDeclarations be the LexicallyScopedDeclarations of script.
For each element d in lexDeclarations, do
NOTE: Lexically declared names are only instantiated here but not initialized.
早期错误 specified in 15.1.1 prevent name conflicts between function/var declarations and let/const/class declarations as well as redeclaration of let/const/class bindings for declaration contained within a single Script. However, such conflicts and redeclarations that span more than one Script are detected as runtime errors during GlobalDeclarationInstantiation. If any such errors are detected, no bindings are instantiated for the script. However, if the 全局对象 is defined using Proxy 外来对象 then the runtime tests for conflicting declarations may be unreliable resulting in an abrupt completion and some global declarations not being instantiated. If this occurs, the code for the Script is not evaluated.
Unlike explicit var or 函数声明, properties that are directly created on the 全局对象 result in global bindings that may be shadowed by let/const/class declarations.
这是一个句法错误如果 the LexicallyDeclaredNames of ModuleItemList contains any duplicate entries.
这是一个句法错误如果 any element of the LexicallyDeclaredNames of ModuleItemList also occurs in the VarDeclaredNames of ModuleItemList.
这是一个句法错误如果 the ExportedNames of ModuleItemList contains any duplicate entries.
这是一个句法错误如果 any element of the ExportedBindings of ModuleItemList does not also occur in either the VarDeclaredNames of ModuleItemList, or the LexicallyDeclaredNames of ModuleItemList.
这是一个句法错误如果 ContainsDuplicateLabels of ModuleItemList with argument « » is true.
这是一个句法错误如果 ContainsUndefinedBreakTarget of ModuleItemList with argument « » is true.
这是一个句法错误如果 ContainsUndefinedContinueTarget of ModuleItemList with arguments « » and « » is true.
Note
The duplicate ExportedNames rule implies that multiple export defaultExportDeclaration items within a ModuleBody is a Syntax Error. Additional error conditions relating to conflicting or duplicate declarations are checked during module linking prior to 估值 of a Module. If any such errors are detected the Module is not evaluated.
The 抽象操作 ImportedLocalNames with argument importEntries creates a List of all of the local name bindings defined by a List of ImportEntry Records (see Table 40). ImportedLocalNames 执行如下:
A Module Record encapsulates structural information about the imports and exports of a single module. This information is used to link the imports and exports of sets of connected 模块. A Module Record includes four fields that are only used when evaluating a module.
For specification purposes Module Record values are values of the Record 规范类型 and can be thought of as existing in a simple object-oriented hierarchy where Module Record is an abstract class with concrete subclasses. This specification only defines a single Module Record concrete subclass named 源文本 Module Record. Other specifications and implementations may define additional Module Record subclasses corresponding to alternative module definition facilities that they defined.
Module Record defines the fields listed in Table 37. All Module Definition subclasses include at least those fields. Module Record also defines the abstract method list in Table 38. All Module definition subclasses must provide concrete implementations of these abstract methods.
The 词法环境 containing the top level bindings for this module. This field is set when the module is instantiated.
[[命名空间]]
Object | undefined
The 模块命名空间对象 (26.3) if one has been created for this module. Otherwise undefined.
[[HostDefined]]
Any, 默认值 is undefined.
Field reserved for use by 宿主环境 that need to associate additional information with a module.
Table 38: Abstract Methods of Module Records
Method
Purpose
GetExportedNames(exportStarSet)
Return a list of all names that are either directly or indirectly exported from this module.
ResolveExport(exportName, resolveSet)
Return the binding of a name exported by this module. Bindings are represented by a ResolvedBinding Record, of the form {[[Module]]: Module Record, [[BindingName]]: String}. Return null if the name cannot be resolved, or "ambiguous" if multiple bindings were found.
This operation must be idempotent if it completes normally. Each time it is called with a specific exportName, resolveSet pair as arguments it must return the same result.
Instantiate()
Prepare the module for 估值 by transitively resolving all module dependencies and creating a module 环境记录.
Evaluate()
If this module has already been evaluated successfully, return undefined; if it has already been evaluated unsuccessfully, throw the 异常 that was produced. Otherwise, transitively evaluate all module dependencies of this module and then evaluate this module.
Instantiate must have completed successfully prior to invoking this method.
15.2.1.16源文本模块记录
A 源文本 Module Record is used to represent information about a module that was defined from ES 源文本 (10) that was parsed using the 目标符Module. Its fields contain digested information about the names that are imported by the module and its concrete methods use this digest to link, instantiate, and evaluate the module.
A 源文本 Module Record can exist in a module graph with other subclasses of the abstract Module Record type. However, non-源文本模块记录 must not participate in dependency cycles with 源文本模块记录.
In addition to the fields, defined in Table 37, 源文本模块记录 have the additional fields listed in Table 39. Each of these fields is initially set in ParseModule.
A List of all the ModuleSpecifier strings used by the module represented by this record to request the importation of a module. The List is source code occurrence ordered.
A List of ExportEntry records derived from the code of this module that correspond to export * declarations that occur within the module.
[[Status]]
String
Initially "uninstantiated". Transitions to "instantiating", "instantiated", "evaluating", "evaluated" (in that order) as the module progresses throughout its lifecycle.
A completion of type throw representing the 异常 that occurred during 估值. undefined if no 异常 occurred or if [[Status]] is not "evaluated".
[[DFSIndex]]
Integer | undefined
Auxiliary field used during Instantiate and Evaluate only.
If [[Status]] is "instantiating" or "evaluating", this non-negative number records the point at which the module was first visited during the ongoing depth-first traversal of the dependency graph.
[[DFSAncestorIndex]]
Integer | undefined
Auxiliary field used during Instantiate and Evaluate only. If [[Status]] is "instantiating" or "evaluating", this is either the module's own [[DFSIndex]] or that of an "earlier" module in the same strongly connected component.
An ImportEntry Record is a Record that digests information about a single declarative import. Each ImportEntry Record has the fields defined in Table 40:
The name under which the desired binding is exported by the module identified by [[ModuleRequest]]. The value "*" indicates that the import request is for the target module's 命名空间 object.
[[LocalName]]
String
The name that is used to locally access the imported value from within the importing module.
Note 1
Table 41 gives examples of ImportEntry records fields used to represent the syntactic import forms:
Table 41 (Informative): Import Forms Mappings to ImportEntry Records
An ExportEntry Record is a Record that digests information about a single declarative export. Each ExportEntry Record has the fields defined in Table 42:
The name under which the desired binding is exported by the module identified by [[ModuleRequest]]. null if the ExportDeclaration does not have a ModuleSpecifier. "*" indicates that the export request is for all exported bindings.
[[LocalName]]
String | null
The name that is used to locally access the exported value from within the importing module. null if the exported value is not locally accessible from within the module.
Note 2
Table 43 gives examples of the ExportEntry record fields used to represent the syntactic export forms:
Table 43 (Informative): Export Forms Mappings to ExportEntry Records
Export Statement Form
[[ExportName]]
[[ModuleRequest]]
[[ImportName]]
[[LocalName]]
export var v;
"v"
null
null
"v"
export default function f(){}
"default"
null
null
"f"
export default function(){}
"default"
null
null
"*default*"
export default 42;
"default"
null
null
"*default*"
export {x};
"x"
null
null
"x"
export {v as x};
"x"
null
null
"v"
export {x} from "mod";
"x"
"mod"
"x"
null
export {v as x} from "mod";
"x"
"mod"
"v"
null
export * from "mod";
null
"mod"
"*"
null
The following definitions specify the required concrete methods and other 抽象操作 for 源文本模块记录
The 抽象操作 ParseModule with arguments 源文本, realm, and hostDefined creates a 源文本 Module Record based upon the result of parsing 源文本 as a Module. ParseModule 执行如下:
Parse 源文本 using Module as the 目标符 and analyse the parse result for any 早期错误 conditions. If the parse was successful and no 早期错误 were found, let body be the resulting parse tree. Otherwise, let body be a List of one or more SyntaxError or ReferenceError objects representing the parsing errors and/or 早期错误. Parsing and 早期错误 detection may be interweaved in an 实现-dependent manner. If more than one 解析错误 or 早期错误 is present, the number and ordering of 错误对象 in the list is 实现-dependent, but at least one must be present.
If ee.[[LocalName]] is not an element of importedBoundNames, then
Append ee to localExportEntries.
Else,
Let ie be the element of importEntries whose [[LocalName]] is the same as ee.[[LocalName]].
If ie.[[ImportName]] is "*", then
Assert: This is a re-export of an imported 模块命名空间对象.
Append ee to localExportEntries.
Else this is a re-export of a single name,
Append the ExportEntry Record {[[ModuleRequest]]: ie.[[ModuleRequest]], [[ImportName]]: ie.[[ImportName]], [[LocalName]]: null, [[ExportName]]: ee.[[ExportName]] } to indirectExportEntries.
An 实现 may parse module 源文本 and analyse it for 早期错误 conditions prior to the 估值 of ParseModule for that module 源文本. However, the reporting of any errors must be deferred until the point where this specification actually performs ParseModule upon that 源文本.
ResolveExport attempts to resolve an imported binding to the actual defining module and local binding name. The defining module may be the module represented by the Module Record this method was invoked on or some other module that is imported by that module. The parameter resolveSet is used to detect unresolved circular import/export paths. If a pair consisting of specific Module Record and exportName is reached that is already in resolveSet, an import circularity has been encountered. Before recursively calling ResolveExport, a pair consisting of module and exportName is added to resolveSet.
If a defining module is found, a ResolvedBinding Record {[[Module]], [[BindingName]]} is returned. This record identifies the resolved binding of the originally requested export. If no definition was found or the request is found to be circular, null is returned. If the request is found to be ambiguous, the string "ambiguous" is returned.
If starResolution is null, set starResolution to resolution.
Else,
Assert: There is more than one * import that includes the requested name.
If resolution.[[Module]] and starResolution.[[Module]] are not the same Module Record or SameValue(resolution.[[BindingName]], starResolution.[[BindingName]]) is false, return "ambiguous".
On success, Instantiate transitions this module's [[Status]] from "uninstantiated" to "instantiated". On failure, an 异常 is thrown and this module's [[Status]] remains "uninstantiated".
This abstract method 执行如下 (most of the work is done by the auxiliary function InnerModuleInstantiation):
15.2.1.16.4.1InnerModuleInstantiation( module, stack, index )
The InnerModuleInstantiation 抽象操作 is used by Instantiate to perform the actual instantiation process for the 源文本 Module Recordmodule, as well as recursively on all other 模块 in the dependency graph. The stack and index parameters, as well as a module's [[DFSIndex]] and [[DFSAncestorIndex]] fields, keep track of the depth-first search (DFS) traversal. In particular, [[DFSAncestorIndex]] is used to discover strongly connected components (SCCs), such that all 模块 in an SCC transition to "instantiated" together.
The ModuleDeclarationEnvironmentSetup 抽象操作 is used by InnerModuleInstantiation to initialize the 词法环境 of the module, including resolving all imported bindings.
NOTE: The above call cannot fail because imported module requests are a subset of module.[[RequestedModules]], and these have been resolved earlier in this 算法.
15.2.1.16.5.1InnerModuleEvaluation( module, stack, index )
The InnerModuleEvaluation 抽象操作 is used by Evaluate to perform the actual 估值 process for the 源文本 Module Recordmodule, as well as recursively on all other 模块 in the dependency graph. The stack and index parameters, as well as module's [[DFSIndex]] and [[DFSAncestoreIndex]] fields, are used the same way as in InnerModuleInstantiation.
This non-normative section gives a series of examples of the instantiation and 估值 of a few common module graphs, with a specific focus on how errors can occur.
First consider the following simple module graph:
Figure 2: A simple module graph
Let's first assume that there are no error conditions. When a host first calls A.Instantiate(), this will complete successfully by assumption, and recursively instantiate 模块 B and C as well, such that A.[[Status]] = B.[[Status]] = C.[[Status]] = "instantiated". This preparatory step can be performed at any time. Later, when the host is ready to incur any possible side effects of the 模块, it can call A.Evaluate(), which will complete successfully (again by assumption), recursively having evaluated first C and then B. Each module's [[Status]] at this point will be "evaluated".
Consider then cases involving instantiation errors. If InnerModuleInstantiation of C succeeds but, thereafter, fails for B, 例如 because it imports something that C does not provide, then the original A.Instantiate() will fail, and both A and B's [[Status]] remain "uninstantiated". C's [[Status]] has become "instantiated", though.
Finally, consider a case involving 估值 errors. If InnerModuleEvaluation of C succeeds but, thereafter, fails for B, 例如 because B contains code that throws an 异常, then the original A.Evaluate() will fail. The resulting 异常 will be recorded in both A and B's [[EvaluationError]] fields, and their [[Status]] will become "evaluated". C will also become "evaluated" but, in contrast to A and B, will remain without an [[EvaluationError]], as it successfully completed 估值. Storing the 异常 ensures that any time a host tries to reuse A or B by calling their Evaluate() method, it will encounter the same 异常. (Hosts are not required to reuse 源文本模块记录; similarly, hosts are not required to expose the 异常 objects thrown by these methods. However, the specification enables such uses.)
The difference here between instantiation and 估值 errors is due to how 估值 must be only performed once, as it can cause side effects; it is thus important to remember whether 估值 has already been performed, even if unsuccessfully. (In the error case, it makes sense to also remember the 异常 because otherwise subsequent Evaluate() calls would have to synthesize a new one.) Instantiation, on the other hand, is side-effect-free, and thus even if it fails, it can be retried at a later time with no issues.
Now consider a different type of error condition:
Figure 3: A module graph with an unresolvable module
In this scenario, module A declares a dependency on some other module, but no Module Record exists for that module, i.e. HostResolveImportedModule throws an 异常 when asked for it. This could occur for a variety of reasons, 例如 the corresponding resource not existing, or the resource existing but ParseModule throwing an 异常 when trying to parse the resulting 源文本. Hosts can choose to expose the cause of failure via the 异常 they throw from HostResolveImportedModule. In any case, this 异常 causes an instantiation failure, which as before results in A's [[Status]] remaining "uninstantiated".
Lastly, consider a module graph with a cycle:
Figure 4: A cyclic module graph
Here we assume that the entry point is module A, so that the host proceeds by calling A.Instantiate(), which performs InnerModuleInstantiation on A. This in turn calls InnerModuleInstantiation on B. Because of the cycle, this again triggers InnerModuleInstantiation on A, but at this point it is a no-op since A.[[Status]] is already "instantiating". B.[[Status]] itself remains "instantiating" when control gets back to A and InnerModuleInstantiation is triggered on C. After this returns with C.[[Status]] being "instantiated" , both A and B transition from "instantiating" to "instantiated" together; this is by design, since they form a strongly connected component.
An analogous story occurs for the 估值 phase of a cyclic module graph, in the success case.
Now consider a case where A has an instantiation error; 例如, it tries to import a binding from C that does not exist. In that case, the above steps still occur, including the early return from the second call to InnerModuleInstantiation on A. However, once we unwind back to the original InnerModuleInstantiation on A, it fails during ModuleDeclarationEnvironmentSetup, namely right after C.ResolveExport(). The thrown **SyntaxError** 异常 propagates up to A.Instantiate, which resets all 模块 that are currently on its stack (these are always exactly the 模块 that are still "instantiating"). Hence both A and B become "uninstantiated". Note that C is left as "instantiated".
Finally, consider a case where A has an 估值 error; 例如, its source code throws an 异常. In that case, the 估值-time analog of the above steps still occurs, including the early return from the second call to InnerModuleEvaluation on A. However, once we unwind back to the original InnerModuleEvaluation on A, it fails by assumption. The 异常 thrown propagates up to A.Evaluate(), which records the error in all 模块 that are currently on its stack (i.e., the 模块 that are still "evaluating"). Hence both A and B become "errored", while C is left as "evaluated".
HostResolveImportedModule is an 实现-defined 抽象操作 that provides the concrete Module Record subclass instance that corresponds to the ModuleSpecifier String, specifier, occurring within the context of the module represented by the Module RecordreferencingModule.
The 实现 of HostResolveImportedModule must conform to the following requirements:
The normal 返回值 must be an instance of a concrete subclass of Module Record.
If a Module Record corresponding to the pair referencingModule, specifier does not exist or cannot be created, an 异常 must be thrown.
This operation must be idempotent if it completes normally. Each time it is called with a specific referencingModule, specifier pair as arguments it must return the same Module Record instance.
Multiple different referencingModule, specifier pairs may map to the same Module Record instance. The actual mapping semantic is 实现-defined but typically a normalization process is applied to specifier as part of the mapping process. A typical normalization process would include actions 例如 alphabetic case folding and expansion of relative and abbreviated path specifiers.
15.2.1.18运行时语义: GetModuleNamespace( module )
The GetModuleNamespace 抽象操作 retrieves the the Module 命名空间 外来对象 representing module's exports, lazily creating it the first time it was requested, and storing it in module.[[命名空间]] for future retrieval.
The only way GetModuleNamespace can throw is via one of the triggered HostResolveImportedModule calls. Unresolvable names are simply excluded from the 命名空间 at this point. They will lead to a real instantiation error later unless they are all ambiguous star exports that are not explicitly requested anywhere.
Assert: All dependencies of m have been transitively resolved and m is ready for 估值.
Return ? m.Evaluate().
Note
An 实现 may parse a 源文本 as a Module, analyse it for 早期错误 conditions, and instantiate it prior to the execution of the TopLevelModuleEvaluationJob for that 源文本. An 实现 may also resolve, pre-parse and pre-analyse, and pre-instantiate module dependencies of 源文本. However, the reporting of any errors detected by these actions must be deferred until the TopLevelModuleEvaluationJob is actually executed.
For each IdentifierNamen in ReferencedBindings of ExportClause: 这是一个句法错误如果 字符值 of n is a ReservedWord or if the 字符值 of n is one of: "implements", "interface", "let", "package", "private", "protected", "public", or "static".
Return a new List containing the ExportEntry Record {[[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default"}.
Return a new List containing the ExportEntry Record {[[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default"}.
Return a new List containing the ExportEntry Record {[[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: sourceName }.
Return a new List containing the ExportEntry Record {[[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: exportName }.
It is not necessary to treat export defaultAssignmentExpression as a constant declaration because there is no syntax that permits assignment to the internal bound name used to reference a module's default object.
An 实现 must report most errors at the time the relevant ES language construct is evaluated. An 早期错误 is an error that can be detected and reported prior to the 估值 of any construct in the Script containing the error. The presence of an 早期错误 prevents the 估值 of the construct. An 实现 must report 早期错误 in a Script as part of parsing that Script in ParseScript. 早期错误 in a Module are reported at the point when the Module would be evaluated and the Module is never initialized. 早期错误 in eval code are reported at the time eval is called and prevent 估值 of the eval code. All errors that are not 早期错误 are runtime errors.
An 实现 must report as an 早期错误 any occurrence of a condition that is listed in a “静态语义: 早期错误” subclause of this specification.
An 实现 shall not treat other kinds of errors as 早期错误 even if the compiler can prove that a construct cannot execute without error under any circumstances. An 实现 may issue an early warning in such a case, but it should not report the error until the relevant construct is actually executed.
An 实现 shall report all errors as specified, except for the following:
Except as restricted in 16.2, an 实现 may extend Script syntax, Module syntax, and 正则表达式 pattern or flag syntax. To permit this, all operations (例如 calling eval, using a 正则表达式 literal, or using the Function or RegExp构造器) that are allowed to throw SyntaxError are permitted to exhibit 实现-defined behaviour instead of throwing SyntaxError when they encounter an 实现-defined extension to the script syntax or 正则表达式 pattern or flag syntax.
Except as restricted in 16.2, an 实现 may provide additional types, values, objects, properties, and functions beyond those described 在本规范中. This may cause constructs (例如 looking up a variable in the global scope) to have 实现-defined behaviour instead of throwing an error (例如 ReferenceError).
16.1HostReportErrors ( errorList )
HostReportErrors is an 实现-defined 抽象操作 that allows 宿主环境 to report parsing errors, 早期错误, and runtime errors.
An 实现 of HostReportErrors must complete normally in all cases. The default 实现 of HostReportErrors is to unconditionally return an empty normal completion.
Note
errorList will be a List of ES 语言值. If the errors are parsing errors or 早期错误, these will always be SyntaxError or ReferenceError objects. Runtime errors, however, can be any ES 值.
16.2禁止扩展
An 实现 must not extend this specification in the following ways:
If an 实现 extends any 函数对象 with an 自身属性 named "caller" the value of that property, as observed using [[Get]] or [[GetOwnProperty]], must not be a strict function object. If it is an 访问器属性, the function that is the value of the property's [[Get]] 特性 must never return a strict function when called.
Neither mapped nor unmapped arguments objects may be created with an 自身属性 named "caller".
The behaviour of the following methods must not be extended except as specified in ECMA-402: Object.prototype.toLocaleString, Array.prototype.toLocaleString, Number.prototype.toLocaleString, Date.prototype.toLocaleDateString, Date.prototype.toLocaleString, Date.prototype.toLocaleTimeString, String.prototype.localeCompare, %TypedArray%.prototype.toLocaleString.
The RegExp pattern grammars in 21.2.1 and B.1.4 must not be extended to recognize any of the source characters A-Z or a-z as IdentityEscape[+U] when the [U] grammar parameter is present.
句法 must not be extended in any manner that allows the token : to immediately follow 源文本 that matches the BindingIdentifier 非终止符.
许多内置对象是函数:它们可以通过参数调用。其中有些还可以作为构造器:这些函数可被 new 运算符调用。对于每个内置函数,本规范描述了这些函数的必须参数和函数对象的属性。对于每个内置构造器,本规范还描述了这些构造器的 prototype 对象的属性,还描述了用 new 表达式调用这个构造器后返回的具体实例对象的属性。
除非对某一特定函数的描述另有规定,如果一个内置函数或构造器在被调用时传入的参数少于必须的参数个数,那么这个函数或构造器将表现为仿佛传入了足够的参数,而那些缺少的参数会设定为 undefined 值。这些遗失的参数会被认为是“不存在的” and may be identified in that manner by specification 算法. In the description of a particular function, the terms “this value” and “NewTarget” have the meanings given in 9.3.
例如, the 函数对象 that is the 初始值 of the map property of the Array 原型对象 is described under the subclause heading «Array.prototype.map (callbackFn [ , thisArg])» which shows the two named arguments callbackFn and thisArg, the latter being optional; therefore the value of the length property of that 函数对象 is 1.
每个不被确定为匿名函数的内置函数对象,包括构造器,都有一个值为字符串的 name 属性。除非另有规定,本规范中,这个 name 的值由函数给出。对于被指定为对象属性的函数,这个 name 的值就是用来访问该函数的属性名字符串。Functions that are specified as get or set accessor functions of 内置 properties have "get " or "set " prepended to the 属性名 string. 对于属性值是符号值的每个内置函数,属性 name 的值被显示地指定。
Unless otherwise specified, the name property of a 内置 函数对象, if it exists, has the 特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
Every other 数据属性 described in clauses 18 through 26 and in Annex B.2 has the 特性 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true } unless otherwise specified.
Every 访问器属性 described in clauses 18 through 26 and in Annex B.2 has the 特性 { [[Enumerable]]: false, [[Configurable]]: true } unless otherwise specified. If only a get 访问器函数 is described, the set 访问器函数 is the 默认值, undefined. If only a set accessor is described the get accessor is the 默认值, undefined.
If F.[[ConstructorKind]] is "derived", let inDerivedConstructor be true; otherwise, let inDerivedConstructor be false.
Else,
Let inFunction be false.
Let inMethod be false.
Let inDerivedConstructor be false.
Let script be the ES 代码 that is the result of parsing x, interpreted as UTF-16 encoded Unicode text as described in 6.1.4, for the 目标符Script. If inFunction is false, additional 早期错误 rules from 18.2.1.1.1 are applied. If inMethod is false, additional 早期错误 rules from 18.2.1.1.2 are applied. If inDerivedConstructor is false, additional 早期错误 rules from 18.2.1.1.3 are applied. If the parse fails, 抛出一个 SyntaxError 异常. If any 早期错误 are detected, 抛出一个 SyntaxError or a ReferenceError 异常, depending on the type of the error (but see also clause 16). Parsing and 早期错误 detection may be interweaved in an 实现-dependent manner.
If script Contains ScriptBody is false, return undefined.
NOTE: If direct is true, ctx will be the 执行上下文 that performed the direct eval. If direct is false, ctx will be the 执行上下文 for the invocation of the eval function.
The eval code cannot instantiate variable or function bindings in the variable environment of the calling context that invoked the eval if the calling context is evaluating formal parameter 初始化器 or if either the code of the calling context or the eval code is 严格模式代码. Instead such bindings are instantiated in a new VariableEnvironment that is only accessible to the eval code. Bindings introduced by let, const, or class declarations are always instantiated in a new LexicalEnvironment.
18.2.1.1.1Additional 早期错误 Rules for Eval Outside Functions
HostEnsureCanCompileStrings is an 实现-defined 抽象操作 that allows 宿主环境 to block certain ES functions which allow developers to compile strings into ES 代码.
An 实现 of HostEnsureCanCompileStrings may complete normally or abruptly. Any abrupt completions will be propagated to its callers. The default 实现 of HostEnsureCanCompileStrings is to unconditionally return an empty normal completion.
Let trimmedString be a substring of inputString consisting of the leftmost 代码单元 that is not a StrWhiteSpaceChar and all 代码单元 to the right of that 代码单元. (In other words, remove leading 空白.) If inputString does not contain any such 代码单元, let trimmedString be the empty string.
If neither trimmedString nor any prefix of trimmedString satisfies the syntax of a StrDecimalLiteral (see 7.1.3.1), return NaN.
Let numberString be the longest prefix of trimmedString, which might be trimmedString itself, that satisfies the syntax of a StrDecimalLiteral.
Let mathFloat be MV of numberString.
If mathFloat=0, then
If the first 代码单元 of trimmedString is the 代码单元 0x002D (HYPHEN-MINUS), return -0.
Return +0.
Return the Number 值 for mathFloat.
Note
parseFloat may interpret only a leading portion of string as a Number 值; it ignores any 代码单元 that cannot be interpreted as part of the notation of a decimal literal, and no indication is given that any such 代码单元 were ignored.
18.2.5parseInt ( string, radix )
The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading 空白 in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the 代码单元 pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, the number may also optionally begin with the 代码单元 pairs 0x or 0X.
The parseInt function is the %parseInt% 内部对象. When the parseInt function is called, 执行如下:
Let S be a newly created substring of inputString consisting of the first 代码单元 that is not a StrWhiteSpaceChar and all 代码单元 following that 代码单元. (In other words, remove leading 空白.) If inputString does not contain any such 代码单元, let S be the empty string.
Let sign be 1.
If S is not empty and the first 代码单元 of S is the 代码单元 0x002D (HYPHEN-MINUS), let sign be -1.
If S is not empty and the first 代码单元 of S is the 代码单元 0x002B (PLUS SIGN) or the 代码单元 0x002D (HYPHEN-MINUS), remove the first 代码单元 from S.
If the length of S is at least 2 and the first two 代码单元 of S are either "0x" or "0X", remove the first two 代码单元 from S and let R be 16.
If S contains a 代码单元 that is not a radix-R digit, let Z be the substring of S consisting of all 代码单元 before the first such 代码单元; otherwise, let Z be S.
If Z is empty, return NaN.
Let mathInt be the mathematical integer value that is represented by Z in radix-R notation, using the letters A-Z and a-z for digits with values 10 through 35. (However, if R is 10 and Z contains more than 20 significant digits, every significant digit after the 20th may be replaced by a 0 digit, at the option of the 实现; and if R is not 2, 4, 8, 10, 16, or 32, then mathInt may be an 实现-dependent approximation to the mathematical integer value that is represented by Z in radix-R notation.)
If mathInt = 0, then
If sign = -1, return -0.
Return +0.
Let number be the Number 值 for mathInt.
Return sign × number.
Note
parseInt may interpret only a leading portion of string as an integer value; it ignores any 代码单元 that cannot be interpreted as part of the notation of an integer, and no indication is given that any such 代码单元 were ignored.
18.2.6URI 处理函数
Uniform Resource 标识符, or URIs, are Strings that identify resources (e.g. web pages or files) and transport protocols by which to access them (e.g. HTTP or FTP) on the Internet. The ES language itself does not provide any support for using URIs except for functions that encode and decode URIs as described in 18.2.6.2, 18.2.6.3, 18.2.6.4 and 18.2.6.5
Note
Many implementations of ES provide additional functions and methods that manipulate web pages; these functions are beyond the scope of this standard.
18.2.6.1URI 句法和语义
A URI is composed of a sequence of components separated by component separators. The general form is:
Scheme:First/Second;Third?Fourth
where the italicized names represent components and “:”, “/”, “;” and “?” are reserved for use as separators. The encodeURI and decodeURI functions are intended to work with complete URIs; they assume that any reserved 代码单元 in the URI are intended to have special meaning and so are not encoded. The encodeURIComponent and decodeURIComponent functions are intended to work with the individual component parts of a URI; they assume that any reserved 代码单元 represent text and so must be encoded so that they are not interpreted as reserved 代码单元 when the component is part of a complete URI.
The following 词法 specifies the form of encoded URIs.
The above syntax is based upon RFC 2396 and does not reflect changes introduced by the more recent RFC 3986.
运行时语义
When a 代码单元 to be included in a URI is not listed above or is not intended to have the special meaning sometimes given to the reserved 代码单元, that 代码单元 must be encoded. The 代码单元 is transformed into its UTF-8 encoding, with surrogate pairs first converted from UTF-16 to the corresponding 码点 value. (Note that for 代码单元 in the range [0,127] this results in a single octet with the same value.) The resulting sequence of octets is then transformed into a String with each octet represented by an escape sequence of the form "%xx".
18.2.6.1.1运行时语义: Encode ( string, unescapedSet )
The encoding and escaping process is described by the 抽象操作 Encode taking two String arguments string and unescapedSet.
This syntax of Uniform Resource 标识符 is based upon RFC 2396 and does not reflect the more recent RFC 3986 which replaces RFC 2396. A formal description and 实现 of UTF-8 is given in RFC 3629.
In UTF-8, characters are encoded using sequences of 1 to 6 octets. The only octet of a sequence of one has the higher-order bit set to 0, the remaining 7 bits being used to encode the character value. In a sequence of n octets, n>1, the initial octet has the n higher-order bits set to 1, followed by a bit set to 0. The remaining bits of that octet contain bits from the value of the character to be encoded. The following octets all have the higher-order bit set to 1 and the following bit set to 0, leaving 6 bits in each to contain bits from the character to be encoded. The possible UTF-8 encodings of ES characters are specified in Table 44.
Table 44 (Informative): UTF-8 Encodings
代码单元 Value
Representation
1st Octet
2nd Octet
3rd Octet
4th Octet
0x0000 - 0x007F
00000000 0zzzzzzz
0zzzzzzz
0x0080 - 0x07FF
00000yyy yyzzzzzz
110yyyyy
10zzzzzz
0x0800 - 0xD7FF
xxxxyyyy yyzzzzzz
1110xxxx
10yyyyyy
10zzzzzz
0xD800 - 0xDBFF
followed by
0xDC00 - 0xDFFF
110110vv vvwwwwxx
followed by
110111yy yyzzzzzz
11110uuu
10uuwwww
10xxyyyy
10zzzzzz
0xD800 - 0xDBFF
not followed by
0xDC00 - 0xDFFF
causes URIError
0xDC00 - 0xDFFF
causes URIError
0xE000 - 0xFFFF
xxxxyyyy yyzzzzzz
1110xxxx
10yyyyyy
10zzzzzz
Where
uuuuu = vvvv + 1
to account for the addition of 0x10000 as in Surrogates, section 3.8, of the Unicode Standard.
The range of 代码单元 values 0xD800-0xDFFF is used to encode surrogate pairs; the above transformation combines a UTF-16 代理对 into a UTF-32 representation and encodes the resulting 21-bit value in UTF-8. Decoding reconstructs the 代理对.
RFC 3629 prohibits the decoding of invalid UTF-8 octet sequences. 例如, the invalid sequence C0 80 must not decode into the 代码单元 0x0000. Implementations of the Decode 算法 are required to 抛出一个 URIError when encountering such invalid sequences.
18.2.6.2decodeURI ( encodedURI )
The decodeURI function computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by the encodeURI function is replaced with the UTF-16 encoding of the code points that it represents. Escape sequences that could not have been introduced by encodeURI are not replaced.
The decodeURI function is the %decodeURI% 内部对象. When the decodeURI function is called with one argument encodedURI, 执行如下:
The decodeURIComponent function computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by the encodeURIComponent function is replaced with the UTF-16 encoding of the code points that it represents.
The decodeURIComponent function is the %decodeURIComponent% 内部对象. When the decodeURIComponent function is called with one argument encodedURIComponent, 执行如下:
Let componentString be ? ToString(encodedURIComponent).
The encodeURI function computes a new version of a UTF-16 encoded (6.1.4) URI in which each instance of certain code points is replaced by one, two, three, or four escape sequences representing the UTF-8 encoding of the code points.
The encodeURI function is the %encodeURI% 内部对象. When the encodeURI function is called with one argument uri, 执行如下:
The 代码单元 "#" is not encoded to an escape sequence even though it is not a reserved or unescaped URI 码点.
18.2.6.5encodeURIComponent ( uriComponent )
The encodeURIComponent function computes a new version of a UTF-16 encoded (6.1.4) URI in which each instance of certain code points is replaced by one, two, three, or four escape sequences representing the UTF-8 encoding of the 码点.
The encodeURIComponent function is the %encodeURIComponent% 内部对象. When the encodeURIComponent function is called with one argument uriComponent, 执行如下:
The ordering of steps 1 and 2 is chosen to ensure that any 异常 that would have been thrown by step 1 in previous editions of this specification will continue to be thrown even if the this value is undefined or null.
19.1.3.3Object.prototype.isPrototypeOf ( V )
When the isPrototypeOf method is called with argument V, 执行如下:
The ordering of steps 1 and 2 preserves the behaviour specified by previous editions of this specification for the case where V is not an object and the this value is undefined or null.
19.1.3.4Object.prototype.propertyIsEnumerable ( V )
When the propertyIsEnumerable method is called with argument V, 执行如下:
This method does not consider objects in the prototype chain.
Note 2
The ordering of steps 1 and 2 is chosen to ensure that any 异常 that would have been thrown by step 1 in previous editions of this specification will continue to be thrown even if the this value is undefined or null.
The optional parameters to this function are not used but are intended to correspond to the parameter pattern used by ECMA-402 toLocaleString functions. Implementations that do not include ECMA-402 support must not use those parameter positions for other purposes.
Note 1
This function provides a generic toLocaleString 实现 for objects that have no locale-specific toString behaviour. Array, Number, Date, and Typed Arrays provide their own locale-sensitive toLocaleString methods.
Note 2
ECMA-402 intentionally does not provide an alternative to this default 实现.
19.1.3.6Object.prototype.toString ( )
When the toString method is called, 执行如下:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
Historically, this function was occasionally used to access the String 值 of the [[Class]] 内部属性 that was used in previous editions of this specification as a nominal type tag for various 内置 objects. The above definition of toString preserves compatibility for legacy code that uses toString as a test for those specific kinds of 内置 objects. It does not provide a reliable type testing mechanism for other kinds of 内置 or program defined objects. In addition, programs can use @@toStringTag in ways that will invalidate the reliability of such legacy type tests.
函数构造器是内部对象 %Function% ,也是全局对象的 Function 属性的初始值。当将 Function 作为函数来调用,而不是构造器时,它会创建并初始化一个新的函数对象。所以函数调用 Function(…) 与用相同参数的对象创建表达式 new Function(…) 的效果相同。
函数构造器被设计为可以再细分的,它可能被用作类定义的 extends 语句的值。子类构造器 that 旨在继承特定的 Function behaviour must include a super call to the Function构造器 to create and initialize a subclass instance with the 内部属性 necessary for 内置函数 behaviour. All ES syntactic forms for defining 函数对象 create instances of Function. There is no syntactic means to create instances of Function subclasses except for the 内置 GeneratorFunction, AsyncFunction, and AsyncGeneratorFunction subclasses.
It is permissible but not necessary to have one argument for each formal parameter to be specified. 例如, all three of the following expressions produce the same result:
The 抽象操作 CreateDynamicFunction is called with arguments 构造器, newTarget, kind, and args. 构造器 is the 构造器 function that is performing this action, newTarget is the 构造器 that new was initially applied to, kind is either "normal", "generator", "async", or "async generator", and args is a List containing the actual argument values that were passed to 构造器. 执行如下:
Let parameters be the result of parsing P, interpreted as UTF-16 encoded Unicode text as described in 6.1.4, using parameterGoal as the 目标符. 抛出一个 SyntaxError 异常 if the parse fails.
Let body be the result of parsing bodyText, interpreted as UTF-16 encoded Unicode text as described in 6.1.4, using goal as the 目标符. 抛出一个 SyntaxError 异常 if the parse fails.
Let strict be ContainsUseStrict of body.
If any 静态语义 errors are detected for parameters or body, 抛出一个 SyntaxError or a ReferenceError 异常, depending on the type of the error. If strict is true, the 早期错误 rules for UniqueFormalParameters:FormalParameters are applied. Parsing and 早期错误 detection may be interweaved in an 实现-dependent manner.
If strict is true and IsSimpleParameterList of parameters is false, 抛出一个 SyntaxError 异常.
If any element of the 绑定名 of parameters also occurs in the LexicallyDeclaredNames of body, 抛出一个 SyntaxError 异常.
If body Contains SuperCall is true, 抛出一个 SyntaxError 异常.
If parameters Contains SuperCall is true, 抛出一个 SyntaxError 异常.
If body Contains SuperProperty is true, 抛出一个 SyntaxError 异常.
If parameters Contains SuperProperty is true, 抛出一个 SyntaxError 异常.
If kind is "generator" or "async generator", then
If parameters Contains YieldExpression is true, 抛出一个 SyntaxError 异常.
If kind is "async" or "async generator", then
If parameters Contains AwaitExpression is true, 抛出一个 SyntaxError 异常.
If strict is true, then
If 绑定名 of parameters contains any duplicate elements, 抛出一个 SyntaxError 异常.
A prototype property is created for every non-async function created using CreateDynamicFunction to provide for the possibility that the function will be used as a 构造器.
The thisArg value is passed without modification as the this value. This is a change from Edition 3, where an undefined or nullthisArg is replaced with the 全局对象 and ToObject is applied to all other values and that result is passed as the this value. Even though the thisArg is passed without modification, non-strict functions still perform these transformations upon entry to the function.
Note 2
If func is an arrow function or a bound function then the thisArg will be ignored by the function [[Call]] in step 5.
If this method was called with more than one argument, then in left to right order, starting with the second argument, append each argument as the last element of argList.
The thisArg value is passed without modification as the this value. This is a change from Edition 3, where an undefined or nullthisArg is replaced with the 全局对象 and ToObject is applied to all other values and that result is passed as the this value. Even though the thisArg is passed without modification, non-strict functions still perform these transformations upon entry to the function.
Note 2
If func is an arrow function or a bound function then the thisArg will be ignored by the function [[Call]] in step 5.
19.2.3.4Function.prototype.constructor
The 初始值 of Function.prototype.constructor is the 内部对象 %Function%.
19.2.3.5Function.prototype.toString ( )
When the toString method is called on an object func, 执行如下:
Return an 实现-dependent String source code representation of func. The representation must conform to the rules below. It is 实现-dependent whether the representation includes bound function information or information about the target function.
If Type(func) is Object and is either a 内置 函数对象 or has an [[ECMAScriptCode]] 内部属性, then
Return an 实现-dependent String source code representation of func. The representation must conform to the rules below.
The use and placement of 空白, 行终止符, and semicolons within the representation String is 实现-dependent.
If the object was defined using ES 代码 and the returned string representation is not in the form of a MethodDefinition or GeneratorMethod then the representation must be such that if the string is evaluated, using eval in a lexical context that is equivalent to the lexical context used to create the original object, it will result in a new functionally equivalent object. In that case the returned source code must not mention freely any variables that were not mentioned freely by the original function's source code, even if these “extra” names were originally in scope.
If the 实现 cannot produce a source code string that meets these criteria then it must return a string for which eval will 抛出一个 SyntaxError 异常.
19.2.3.6Function.prototype [ @@hasInstance ] ( V )
When the @@hasInstance method of an object F is called with value V, 执行如下:
This is the default 实现 of @@hasInstance that most functions inherit. @@hasInstance is called by the instanceof 运算符 to determine whether a value is an instance of a specific 构造器. An expression 例如
v instanceof F
evaluates as
F[@@hasInstance](v)
A 构造器 function can control which objects are recognized as its instances by instanceof by exposing a different @@hasInstance method on the function.
This property is non-writable and non-configurable to prevent tampering that could be used to globally expose the target function of a bound function.
19.2.4Function 实例
每一个 Function 实例都是一个 ES 函数对象,和都有这些列在 Table 27 中内部属性。使用 Function.prototype.bind 方法创建的 Function 对象的内部属性列在 Table 28 中。
Function 实例有以下属性:
19.2.4.1length
The value of the length property is an integer that indicates the typical number of arguments expected by the function. However, the language permits the function to be invoked with some other number of arguments. The behaviour of a function when invoked on a number of arguments other than the number specified by its length property depends on the function. 该属性拥有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.length 属性值是一个整数,它指出函数预期的参数个数。然而,语言允许用其他数量的参数来调用函数。当以与函数的 length 属性指定的数量不同的参数个数调用函数时,它的行为依赖于函数自身。这个属性拥有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }。
19.2.4.2name
The value of the name property is a String that is descriptive of the function. The name has no semantic significance but is typically a variable or 属性名 that is used to refer to the function at its point of definition in ES 代码. 该属性拥有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
Anonymous functions objects that do not have a contextual name associated with them by this specification do not have a name 自身属性 but inherit the name property of %FunctionPrototype%.
19.2.4.3prototype
可以用来作为一个构造器的 Function 实例有一个 prototype 属性。Whenever such a Function instance is created another 普通对象 is also created and is the 初始值 of the function's prototype property. Unless otherwise specified, the value of the prototype property is used to initialize the [[Prototype]] 内部属性 of the object created when that function is invoked as a 构造器.
The Boolean 构造器 is the %Boolean% 内部对象 and the 初始值 of the Boolean property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 Boolean 对象. When Boolean 被作为一个函数调用而不是一个 构造器, 它会执行一个类型转换.
The Boolean构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 Boolean behaviour must include a super call to the Boolean构造器 以便创建和初始化子类实例 with a [[BooleanData]] 内部属性.
The Boolean 原型对象 is the 内部对象 %BooleanPrototype%. The Boolean 原型对象 is an 普通对象. The Boolean prototype is itself a Boolean 对象; it has a [[BooleanData]] 内部属性 with the value false.
[[Prototype]] 内部属性的值 of the Boolean 原型对象 is the 内部对象 %ObjectPrototype%.
Boolean instances are 普通对象 that 继承属性 from the Boolean 原型对象. Boolean instances have a [[BooleanData]] 内部属性. The [[BooleanData]] 内部属性 is the Boolean 值 represented by this Boolean 对象.
19.4符号对象
19.4.1符号构造器
The Symbol 构造器 is the %Symbol% 内部对象 and the 初始值 of the Symbol property of the 全局对象. When Symbol is called as a function, it returns a new Symbol 值.
The Symbol构造器 is not intended to be used with new 运算符 or to be subclassed. 它可以用作 the value of an extends clause of a class definition but a super call to the Symbol构造器 will cause an 异常.
19.4.1.1Symbol ( [ description ] )
When Symbol is called with 可选参数 description, 执行如下:
If NewTarget is not undefined, 抛出一个 TypeError 异常.
If description is undefined, let descString be undefined.
For each element e of the GlobalSymbolRegistry List, do
If SameValue(e.[[Key]], stringKey) is true, return e.[[Symbol]].
Assert: GlobalSymbolRegistry does not currently contain an entry for stringKey.
Let newSymbol be a new unique Symbol 值 whose [[Description]] value is stringKey.
Append the Record { [[Key]]: stringKey, [[Symbol]]: newSymbol } to the GlobalSymbolRegistry List.
Return newSymbol.
The GlobalSymbolRegistry is a List that is globally available. It is shared by all 范围. Prior to the 估值 of any ES 代码 it is initialized as a new empty List. Elements of the GlobalSymbolRegistry are Records with the structure defined in Table 45.
Symbol instances are 普通对象 that 继承属性 from the Symbol 原型对象. Symbol instances have a [[SymbolData]] 内部属性. The [[SymbolData]] 内部属性 is the Symbol 值 represented by this Symbol 对象.
19.5错误对象
Instances of 错误对象 are thrown as exceptions when runtime errors occur. The 错误对象 may also serve as base objects for user-defined 异常 classes.
19.5.1错误构造器
The Error 构造器 is the %Error% 内部对象 and the 初始值 of the Error property of the 全局对象. When Error 被作为一个函数调用而不是一个 构造器, 它会创建和初始化一个新的 Error object. Thus the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.
The Error构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 Error behaviour must include a super call to the Error构造器 to create and initialize subclass instances with an [[ErrorData]] 内部属性.
19.5.1.1Error ( message )
When the Error function is called with argument message, 执行如下:
If NewTarget is undefined, let newTarget be the active 函数对象, else let newTarget be NewTarget.
If msg is undefined, let msg be the empty String; otherwise let msg be ? ToString(msg).
If name is the empty String, return msg.
If msg is the empty String, return name.
Return the string-concatenation of name, the 代码单元 0x003A (COLON), the 代码单元 0x0020 (SPACE), and msg.
19.5.4错误实例的属性
Error instances are 普通对象 that 继承属性 from the Error 原型对象 and have an [[ErrorData]] 内部属性 whose value is undefined. The only specified uses of [[ErrorData]] is to identify Error and NativeError instances as 错误对象 within Object.prototype.toString.
19.5.5本标准使用的原生错误类型
A new instance of one of the NativeError objects below is thrown when a runtime error is detected. All of these objects share the same structure, as described in 19.5.6.
19.5.5.1EvalError
This 异常 is not currently used within this specification. This object remains for compatibility with previous editions of this specification.
19.5.5.2RangeError
Indicates a value that is not in the set or range of allowable values.
19.5.5.3ReferenceError
Indicate that an invalid reference value has been detected.
19.5.5.4SyntaxError
Indicates that a 解析错误 has occurred.
19.5.5.5TypeError
TypeError is used to indicate an unsuccessful operation when none of the other NativeError objects are an appropriate indication of the failure cause.
19.5.5.6URIError
Indicates that one of the global URI 处理函数 was used in a way that is incompatible with its definition.
19.5.6NativeError 对象结构
When an ES 实现 detects a runtime error, it throws a new instance of one of the NativeError objects defined in 19.5.5. Each of these objects has the structure described below, differing only in the name used as the 构造器 name instead of NativeError, in the name property of the 原型对象, and in the 实现-defined message property of the 原型对象.
For each error object, references to NativeError in the definition should be replaced with the appropriate error object name from 19.5.5.
19.5.6.1NativeError Constructors
When a NativeError构造器 被作为一个函数调用而不是一个 构造器, 它会创建和初始化一个新的 NativeError object. A call of the object as a function is equivalent to calling it as a 构造器 with the same arguments. Thus the function call NativeError(…) is equivalent to the object creation expression new NativeError(…) with the same arguments.
Each NativeError构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 NativeError behaviour must include a super call to the NativeError构造器 to create and initialize subclass instances with an [[ErrorData]] 内部属性.
19.5.6.1.1NativeError ( message )
When a NativeError function is called with argument message, 执行如下:
If NewTarget is undefined, let newTarget be the active 函数对象, else let newTarget be NewTarget.
The actual value of the string passed in step 2 is either "%EvalErrorPrototype%", "%RangeErrorPrototype%", "%ReferenceErrorPrototype%", "%SyntaxErrorPrototype%", "%TypeErrorPrototype%", or "%URIErrorPrototype%" corresponding to which NativeError构造器 is being defined.
19.5.6.2Properties of the NativeError Constructors
[[Prototype]] 内部属性的值 of a NativeError构造器 is the 内部对象 %Error%.
Each NativeError构造器 has a name property whose value is the String 值 `"NativeError"`.
19.5.6.3Properties of the NativeError Prototype Objects
Each NativeError 原型对象 is an 普通对象. It is not an Error instance and does not have an [[ErrorData]] 内部属性.
[[Prototype]] 内部属性的值 of each NativeError 原型对象 is the 内部对象 %ErrorPrototype%.
19.5.6.3.1NativeError.prototype.constructor
The 初始值 of the 构造器 property of the prototype for a given NativeError构造器 is the corresponding 内部对象 %NativeError% (19.5.6.1).
19.5.6.3.2NativeError.prototype.message
The 初始值 of the message property of the prototype for a given NativeError构造器 is the empty String.
19.5.6.3.3NativeError.prototype.name
The 初始值 of the name property of the prototype for a given NativeError构造器 is the String 值 consisting of the name of the 构造器 (the name used instead of NativeError).
19.5.6.4Properties of NativeError Instances
NativeError instances are 普通对象 that 继承属性 from their NativeError 原型对象 and have an [[ErrorData]] 内部属性 whose value is undefined. The only specified use of [[ErrorData]] is by Object.prototype.toString (19.1.3.6) to identify Error or NativeError instances.
20数字和日期
20.1Number 对象
20.1.1Number 构造器
Number 构造器是 %Number% 内部对象和全局对象的 Number 属性的初始值。当被作为一个构造器调用时,它会创建并初始化一个新的 Number 对象。当 Number 被作为一个函数而不是一个构造器被调用时,它会执行一个类型转换。
Number构造器被设计为可被子类化的。它可以被用作一个类定义的 extends 语句的值。意图继承指定的 Number 对象行为的子类构造器必须包括一个 super 调用,以便于Number构造器去创建和初始化一个带有 [[NumberData]] 内部属性的实例。
The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 that is representable as a Number 值, which is approximately 2.2204460492503130808472633361816 x 10-16.
This function differs from the global isNaN function (18.2.3) in that it does not convert its argument to a Number before determining whether it is NaN.
Number.MIN_VALUE 是 Number 类型中的最小的正有限值,约等于 5 × 10-324。
In the IEEE 754-2008 double precision binary representation, the smallest possible value is a denormalized number. If an 实现 does not support denormalized values, the value of Number.MIN_VALUE must be the smallest non-zero positive value that can actually be represented by the 实现.
The phrase “this Number 值” within the specification of a method refers to the result returned by calling the 抽象操作 thisNumberValue with the this value of the method invocation passed as the argument.
Return a String containing this Number 值 represented in decimal exponential notation with one digit before the significand's decimal point and fractionDigits digits after the significand's decimal point. If fractionDigits is undefined, include as many significand digits as necessary to uniquely specify the Number (just like in ToString except that in this case the Number is always output in exponential notation). Specifically, perform the following steps:
Let m be the String 值 consisting of f+1 occurrences of the 代码单元 0x0030 (DIGIT ZERO).
Let e be 0.
Else x ≠ 0,
If fractionDigits is not undefined, then
Let e and n be integers such that 10f ≤ n < 10f+1 and for which the exact 数学值 of n × 10e-f - x is as close to zero as possible. If there are two such sets of e and n, pick the e and n for which n × 10e-f is larger.
Else fractionDigits is undefined,
Let e, n, and f be integers such that f ≥ 0, 10f ≤ n < 10f+1, the Number 值 for n × 10e-f is x, and f is as small as possible. Note that the decimal representation of n has f+1 digits, n is not divisible by 10, and the least significant digit of n is not necessarily uniquely determined by these criteria.
Let m be the String 值 consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
If f ≠ 0, then
Let a be the first element of m, and let b be the remaining f elements of m.
For implementations that provide more accurate conversions than required by the rules above, it is recommended that the following alternative version of step 10.b.i be used as a guideline:
Let e, n, and f be integers such that f ≥ 0, 10f ≤ n < 10f+1, the Number 值 for n × 10e-f is x, and f is as small as possible. If there are multiple possibilities for n, choose the value of n for which n × 10e-f is closest in value to x. If there are two such possible values of n, choose the one that is even.
toFixed returns a String containing this Number 值 represented in decimal fixed-point notation with fractionDigits digits after the decimal point. If fractionDigits is undefined, 0 is assumed.
Let n be an integer for which the exact 数学值 of n ÷ 10f - x is as close to zero as possible. If there are two such n, pick the larger n.
If n = 0, let m be the String "0". Otherwise, let m be the String 值 consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
If f ≠ 0, then
Let k be the length of m.
If k ≤ f, then
Let z be the String 值 consisting of f+1-k occurrences of the 代码单元 0x0030 (DIGIT ZERO).
The output of toFixed may be more precise than toString for some values because toString only prints enough significant digits to distinguish the number from adjacent number values. 例如,
(1000000000000000128).toString() returns "1000000000000000100", while
(1000000000000000128).toFixed(0) returns "1000000000000000128".
An ES 实现 that includes the ECMA-402 Internationalization API must implement the Number.prototype.toLocaleString method as specified in the ECMA-402 specification. If an ES 实现 does not include the ECMA-402 API the following specification of the toLocaleString method is used.
Produces a String 值 that represents this Number 值 formatted according to the conventions of the host environment's current locale. This function is 实现-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.
The meanings of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
Return a String containing this Number 值 represented either in decimal exponential notation with one digit before the significand's decimal point and precision-1 digits after the significand's decimal point or in decimal fixed notation with precision significant digits. If precision is undefined, call ToString instead. Specifically, perform the following steps:
Let m be the String 值 consisting of p occurrences of the 代码单元 0x0030 (DIGIT ZERO).
Let e be 0.
Else x ≠ 0,
Let e and n be integers such that 10p-1 ≤ n < 10p and for which the exact 数学值 of n × 10e-p+1 - x is as close to zero as possible. If there are two such sets of e and n, pick the e and n for which n × 10e-p+1 is larger.
Let m be the String 值 consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
Let m be the string-concatenation of the first e+1 elements of m, the 代码单元 0x002E (FULL STOP), and the remaining p- (e+1) elements of m.
Else e < 0,
Let m be the string-concatenation of the 代码单元 0x0030 (DIGIT ZERO), the 代码单元 0x002E (FULL STOP), -(e+1) occurrences of the 代码单元 0x0030 (DIGIT ZERO), and the String m.
The optional radix should be an integer value in the inclusive range 2 to 36. If radix is not present or is undefined the Number 10 is used as the value of radix.
Return the String representation of this Number 值 using the radix specified by radixNumber. Letters a-z are used for digits with values 10 through 35. The precise 算法 is 实现-dependent, however the 算法 should be a generalization of that specified in 7.1.12.1.
The toString function is not generic; it throws a TypeError 异常 if its this value is not a Number or a Number 对象. Therefore, it cannot be transferred to other kinds of objects for use as a method.
Each of the following Math object functions applies the ToNumber 抽象操作 to each of its arguments (in left-to-right order if there is more than one). If ToNumber returns an abrupt completion, that 完成记录 is immediately returned. Otherwise, the function performs a computation on the resulting Number 值(s). The value returned by each function is a Number.
In the function descriptions below, the symbols NaN, -0, +0, -∞ and +∞ refer to the Number values described in 6.1.6.
Note
The behaviour of the functions acos, acosh, asin, asinh, atan, atanh, atan2, cbrt, cos, cosh, exp, expm1, hypot, log,log1p, log2, log10, pow, random, sin, sinh, sqrt, tan, and tanh is not precisely specified here except to require specific results for certain argument values that represent boundary cases of interest. For other argument values, these functions are intended to compute approximations to the results of familiar 数学函数, but some latitude is allowed in the choice of approximation 算法. The general intent is that an implementer should be able to use the same mathematical library for ES on a given hardware platform that is available to C programmers on that platform.
Although the choice of 算法 is left to the 实现, it is recommended (but not specified by this standard) that implementations use the approximation 算法 for IEEE 754-2008 arithmetic contained in fdlibm, the freely distributable mathematical library from Sun Microsystems (http://www.netlib.org/fdlibm).
20.2.2.1Math.abs ( x )
Returns the absolute value of x; the result has the same magnitude as x but has positive sign.
If x is NaN, the result is NaN.
If x is -0, the result is +0.
If x is -∞, the result is +∞.
20.2.2.2Math.acos ( x )
Returns an 实现-dependent approximation to the arc cosine of x. The result is expressed in radians and ranges from +0 to +π.
If x is NaN, the result is NaN.
If x is greater than 1, the result is NaN.
If x is less than -1, the result is NaN.
If x is exactly 1, the result is +0.
20.2.2.3Math.acosh ( x )
Returns an 实现-dependent approximation to the inverse hyperbolic cosine of x.
If x is NaN, the result is NaN.
If x is less than 1, the result is NaN.
If x is 1, the result is +0.
If x is +∞, the result is +∞.
20.2.2.4Math.asin ( x )
Returns an 实现-dependent approximation to the arc sine of x. The result is expressed in radians and ranges from -π/2 to +π/2.
If x is NaN, the result is NaN.
If x is greater than 1, the result is NaN.
If x is less than -1, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
20.2.2.5Math.asinh ( x )
Returns an 实现-dependent approximation to the inverse hyperbolic sine of x.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
If x is -∞, the result is -∞.
20.2.2.6Math.atan ( x )
Returns an 实现-dependent approximation to the arc tangent of x. The result is expressed in radians and ranges from -π/2 to +π/2.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is an 实现-dependent approximation to +π/2.
If x is -∞, the result is an 实现-dependent approximation to -π/2.
20.2.2.7Math.atanh ( x )
Returns an 实现-dependent approximation to the inverse hyperbolic tangent of x.
If x is NaN, the result is NaN.
If x is less than -1, the result is NaN.
If x is greater than 1, the result is NaN.
If x is -1, the result is -∞.
If x is +1, the result is +∞.
If x is +0, the result is +0.
If x is -0, the result is -0.
20.2.2.8Math.atan2 ( y, x )
Returns an 实现-dependent approximation to the arc tangent of the quotient y/x of the arguments y and x, where the signs of y and x are used to determine the quadrant of the result. Note that it is intentional and traditional for the two-argument arc tangent function that the argument named y be first and the argument named x be second. The result is expressed in radians and ranges from -π to +π.
If either x or y is NaN, the result is NaN.
If y>0 and x is +0, the result is an 实现-dependent approximation to +π/2.
If y>0 and x is -0, the result is an 实现-dependent approximation to +π/2.
If y is +0 and x>0, the result is +0.
If y is +0 and x is +0, the result is +0.
If y is +0 and x is -0, the result is an 实现-dependent approximation to +π.
If y is +0 and x<0, the result is an 实现-dependent approximation to +π.
If y is -0 and x>0, the result is -0.
If y is -0 and x is +0, the result is -0.
If y is -0 and x is -0, the result is an 实现-dependent approximation to -π.
If y is -0 and x<0, the result is an 实现-dependent approximation to -π.
If y<0 and x is +0, the result is an 实现-dependent approximation to -π/2.
If y<0 and x is -0, the result is an 实现-dependent approximation to -π/2.
If y>0 and y is finite and x is +∞, the result is +0.
If y>0 and y is finite and x is -∞, the result is an 实现-dependent approximation to +π.
If y<0 and y is finite and x is +∞, the result is -0.
If y<0 and y is finite and x is -∞, the result is an 实现-dependent approximation to -π.
If y is +∞ and x is finite, the result is an 实现-dependent approximation to +π/2.
If y is -∞ and x is finite, the result is an 实现-dependent approximation to -π/2.
If y is +∞ and x is +∞, the result is an 实现-dependent approximation to +π/4.
If y is +∞ and x is -∞, the result is an 实现-dependent approximation to +3π/4.
If y is -∞ and x is +∞, the result is an 实现-dependent approximation to -π/4.
If y is -∞ and x is -∞, the result is an 实现-dependent approximation to -3π/4.
20.2.2.9Math.cbrt ( x )
Returns an 实现-dependent approximation to the cube root of x.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
If x is -∞, the result is -∞.
20.2.2.10Math.ceil ( x )
Returns the smallest (closest to -∞) Number 值 that is not less than x and is equal to a mathematical integer. If x is already an integer, the result is x.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
If x is -∞, the result is -∞.
If x is less than 0 but greater than -1, the result is -0.
The value of Math.ceil(x) is the same as the value of -Math.floor(-x).
20.2.2.11Math.clz32 ( x )
When Math.clz32 is called with one argument x, 执行如下:
Let p be the number of leading zero bits in the 32-bit binary representation of n.
Return p.
Note
If n is 0, p will be 32. If the most significant bit of the 32-bit binary encoding of n is 1, p will be 0.
20.2.2.12Math.cos ( x )
Returns an 实现-dependent approximation to the cosine of x. The argument is expressed in radians.
If x is NaN, the result is NaN.
If x is +0, the result is 1.
If x is -0, the result is 1.
If x is +∞, the result is NaN.
If x is -∞, the result is NaN.
20.2.2.13Math.cosh ( x )
Returns an 实现-dependent approximation to the hyperbolic cosine of x.
If x is NaN, the result is NaN.
If x is +0, the result is 1.
If x is -0, the result is 1.
If x is +∞, the result is +∞.
If x is -∞, the result is +∞.
Note
The value of cosh(x) is the same as (exp(x) + exp(-x))/2.
20.2.2.14Math.exp ( x )
Returns an 实现-dependent approximation to the exponential function of x (e raised to the power of x, where e is the base of the natural logarithms).
If x is NaN, the result is NaN.
If x is +0, the result is 1.
If x is -0, the result is 1.
If x is +∞, the result is +∞.
If x is -∞, the result is +0.
20.2.2.15Math.expm1 ( x )
Returns an 实现-dependent approximation to subtracting 1 from the exponential function of x (e raised to the power of x, where e is the base of the natural logarithms). The result is computed in a way that is accurate even when the value of x is close 0.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
If x is -∞, the result is -1.
20.2.2.16Math.floor ( x )
Returns the greatest (closest to +∞) Number 值 that is not greater than x and is equal to a mathematical integer. If x is already an integer, the result is x.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
If x is -∞, the result is -∞.
If x is greater than 0 but less than 1, the result is +0.
Note
The value of Math.floor(x) is the same as the value of -Math.ceil(-x).
20.2.2.17Math.fround ( x )
When Math.fround is called with argument x, 执行如下:
If x is NaN, return NaN.
If x is one of +0, -0, +∞, -∞, return x.
Let x32 be the result of converting x to a value in IEEE 754-2008 binary32 format using roundTiesToEven.
Let x64 be the result of converting x32 to a value in IEEE 754-2008 binary64 format.
Return the ES Number 值 corresponding to x64.
20.2.2.18Math.hypot ( value1, value2, ...values )
Math.hypot returns an 实现-dependent approximation of the square root of the sum of squares of its arguments.
If no arguments are passed, the result is +0.
If any argument is +∞, the result is +∞.
If any argument is -∞, the result is +∞.
If no argument is +∞ or -∞, and any argument is NaN, the result is NaN.
If all arguments are either +0 or -0, the result is +0.
Note
Implementations should take care to avoid the loss of precision from overflows and underflows that are prone to occur in naive implementations when this function is called with two or more arguments.
20.2.2.19Math.imul ( x, y )
When Math.imul is called with arguments x and y, 执行如下:
Returns an 实现-dependent approximation to the natural logarithm of x.
If x is NaN, the result is NaN.
If x is less than 0, the result is NaN.
If x is +0 or -0, the result is -∞.
If x is 1, the result is +0.
If x is +∞, the result is +∞.
20.2.2.21Math.log1p ( x )
Returns an 实现-dependent approximation to the natural logarithm of 1 + x. The result is computed in a way that is accurate even when the value of x is close to zero.
If x is NaN, the result is NaN.
If x is less than -1, the result is NaN.
If x is -1, the result is -∞.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
20.2.2.22Math.log10 ( x )
Returns an 实现-dependent approximation to the base 10 logarithm of x.
If x is NaN, the result is NaN.
If x is less than 0, the result is NaN.
If x is +0, the result is -∞.
If x is -0, the result is -∞.
If x is 1, the result is +0.
If x is +∞, the result is +∞.
20.2.2.23Math.log2 ( x )
Returns an 实现-dependent approximation to the base 2 logarithm of x.
If x is NaN, the result is NaN.
If x is less than 0, the result is NaN.
If x is +0, the result is -∞.
If x is -0, the result is -∞.
If x is 1, the result is +0.
If x is +∞, the result is +∞.
20.2.2.24Math.max ( value1, value2, ...values )
Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.
If no arguments are given, the result is -∞.
If any value is NaN, the result is NaN.
The comparison of values to determine the largest value is done using the 抽象关系比较 算法 except that +0 is considered to be larger than -0.
20.2.2.25Math.min ( value1, value2, ...values )
Given zero or more arguments, calls ToNumber on each of the arguments and returns the smallest of the resulting values.
If no arguments are given, the result is +∞.
If any value is NaN, the result is NaN.
The comparison of values to determine the smallest value is done using the 抽象关系比较 算法 except that +0 is considered to be larger than -0.
Returns a Number 值 with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an 实现-dependent 算法 or strategy. This function takes no arguments.
Each Math.random function created for distinct 范围 must produce a distinct sequence of values from successive calls.
20.2.2.28Math.round ( x )
Returns the Number 值 that is closest to x and is equal to a mathematical integer. If two integer Number values are equally close to x, then the result is the Number 值 that is closer to +∞. If x is already an integer, the result is x.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
If x is -∞, the result is -∞.
If x is greater than 0 but less than 0.5, the result is +0.
If x is less than 0 but greater than or equal to -0.5, the result is -0.
Note 1
Math.round(3.5) returns 4, but Math.round(-3.5) returns -3.
Note 2
The value of Math.round(x) is not always the same as the value of Math.floor(x+0.5). When x is -0 or is less than 0 but greater than or equal to -0.5, Math.round(x) returns -0, but Math.floor(x+0.5) returns +0. Math.round(x) may also differ from the value of Math.floor(x+0.5)because of internal rounding when computing x+0.5.
20.2.2.29Math.sign ( x )
Returns the sign of x, indicating whether x is positive, negative, or zero.
If x is NaN, the result is NaN.
If x is -0, the result is -0.
If x is +0, the result is +0.
If x is negative and not -0, the result is -1.
If x is positive and not +0, the result is +1.
20.2.2.30Math.sin ( x )
Returns an 实现-dependent approximation to the sine of x. The argument is expressed in radians.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞ or -∞, the result is NaN.
20.2.2.31Math.sinh ( x )
Returns an 实现-dependent approximation to the hyperbolic sine of x.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
If x is -∞, the result is -∞.
Note
The value of sinh(x) is the same as (exp(x) - exp(-x))/2.
20.2.2.32Math.sqrt ( x )
Returns an 实现-dependent approximation to the square root of x.
If x is NaN, the result is NaN.
If x is less than 0, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +∞.
20.2.2.33Math.tan ( x )
Returns an 实现-dependent approximation to the tangent of x. The argument is expressed in radians.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞ or -∞, the result is NaN.
20.2.2.34Math.tanh ( x )
Returns an 实现-dependent approximation to the hyperbolic tangent of x.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞, the result is +1.
If x is -∞, the result is -1.
Note
The value of tanh(x) is the same as (exp(x) - exp(-x))/(exp(x) + exp(-x)).
20.2.2.35Math.trunc ( x )
Returns the integral part of the number x, removing any fractional digits. If x is already an integer, the result is x.
If x is NaN, the result is NaN.
If x is -0, the result is -0.
If x is +0, the result is +0.
If x is +∞, the result is +∞.
If x is -∞, the result is -∞.
If x is greater than 0 but less than 1, the result is +0.
If x is less than 0 but greater than -1, the result is -0.
20.3Date 对象
20.3.1Date 对象的概述和抽象操作的定义
The following functions are 抽象操作 that operate on time values (defined in 20.3.1.1). Note that, in every case, if any argument to one of these functions is NaN, the result will be NaN.
20.3.1.1时间值和时间范围
A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.
Time is measured in ES in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ES Number values can represent all integers from -9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.
The actual range of times supported by ES 日期对象 is slightly smaller: exactly -100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.
ES uses a proleptic Gregorian calendar to map a day number to a year number and to determine the month and date within that year. In this calendar, leap years are precisely those which are (divisible by 4) and ((not divisible by 100) or (divisible by 400)). The number of days in year number y is therefore defined by
All non-leap years have 365 days with the usual number of days per month and leap years have an extra day in February. The day number of the first day of year y is given by:
A month value of 0 specifies January; 1 specifies February; 2 specifies March; 3 specifies April; 4 specifies May; 5 specifies June; 6 specifies July; 7 specifies August; 8 specifies September; 9 specifies October; 10 specifies November; and 11 specifies December. Note that MonthFromTime(0) = 0, corresponding to Thursday, 01 January, 1970.
20.3.1.5Date Number
A date number is identified by an integer in the range 1 through 31, inclusive. The mapping DateFromTime(t) from a time valuet to a date number is defined by:
A weekday value of 0 specifies Sunday; 1 specifies Monday; 2 specifies Tuesday; 3 specifies Wednesday; 4 specifies Thursday; 5 specifies Friday; and 6 specifies Saturday. Note that WeekDay(0) = 4, corresponding to Thursday, 01 January, 1970.
20.3.1.7LocalTZA ( t, isUTC )
LocalTZA( t, isUTC ) is an 实现-defined 算法 that must return a number representing milliseconds suitable for adding to a Time Value. The local political rules for standard time and daylight saving time in effect at t should be used to determine the result in the way specified in the following three paragraphs.
When isUTC is true, LocalTZA( t, true ) should return the offset of the local time zone from UTC measured in milliseconds at time represented by time valuet (UTC). When the result is added to t (UTC), it should yield the local time.
When isUTC is false, LocalTZA( t, false ) should return the offset of the local time zone from UTC measured in milliseconds at local time represented by time valuetlocal = t. When the result is subtracted from the local time tlocal, it should yield the corresponding UTC.
When tlocal represents local time repeating multiple times at a negative time zone transition (e.g. when the daylight saving time ends or the time zone adjustment is decreased due to a time zone rule change) or skipped local time at a positive time zone transitions (e.g. when the daylight saving time starts or the time zone adjustment is increased due to a time zone rule change), tlocal must be interpreted with the time zone adjustment before the transition.
If an 实现 does not support a conversion described above or if political rules for time t are not available within the 实现, the result must be 0.
Note
It is recommended that implementations use the time zone information of the IANA Time Zone Database https://www.iana.org/time-zones/.
1:30 AM on November 5, 2017 in America/New_York is repeated twice (fall backward), but it must be interpreted as 1:30 AM UTC-04 instead of 1:30 AM UTC-05. LocalTZA(TimeClip(MakeDate(MakeDay(2017, 10, 5), MakeTime(1, 30, 0, 0))), false) is -4 × msPerHour.
2:30 AM on March 12, 2017 in America/New_York does not exist, but it must be interpreted as 2:30 AM UTC-05 (equivalent to 3:30 AM UTC-04). LocalTZA(TimeClip(MakeDate(MakeDay(2017, 2, 12), MakeTime(2, 30, 0, 0))), false) is -5 × msPerHour.
20.3.1.8LocalTime ( t )
The 抽象操作 LocalTime with argument t converts t from UTC to local time by performing the following steps:
Two different time values (t (UTC)) are converted to the same local time tlocal at a negative time zone transition when there are repeated times (e.g. the daylight saving time ends or the time zone adjustment is decreased.).
20.3.1.9UTC ( t )
The 抽象操作 UTC with argument t converts t from local time to UTC. It 执行如下:
Let t be h*msPerHour+m*msPerMinute+s*msPerSecond+milli, performing the arithmetic according to IEEE 754-2008 rules (that is, as if using the ES operators * and +).
Return t.
20.3.1.12MakeDay ( year, month, date )
The 抽象操作 MakeDay calculates a number of days from its three arguments, which must be ES Number values. This 运算符 functions as follows:
If year is not finite or month is not finite or date is not finite, return NaN.
Find a value t such that YearFromTime(t) is ym and MonthFromTime(t) is mn and DateFromTime(t) is 1; but if this is not possible (because some argument is out of range), return NaN.
The point of step 4 is that an 实现 is permitted a choice of internal representations of time values, 例如 as a 64-bit signed integer or as a 64-bit floating-point value. Depending on the 实现, this internal representation may or may not distinguish -0 and +0.
20.3.1.15Date Time String Format
ES defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
Where the fields are as follows:
YYYY
is the decimal digits of the year 0000 to 9999 in the proleptic Gregorian calendar.
-
"-" (hyphen) appears literally twice in the string.
MM
is the month of the year from 01 (January) to 12 (December).
DD
is the day of the month from 01 to 31.
T
"T" appears literally in the string, to indicate the beginning of the time element.
HH
is the number of complete hours that have passed since midnight as two decimal digits from 00 to 24.
:
":" (colon) appears literally twice in the string.
mm
is the number of complete minutes since the start of the hour as two decimal digits from 00 to 59.
ss
is the number of complete seconds since the start of the minute as two decimal digits from 00 to 59.
.
"." (dot) appears literally in the string.
sss
is the number of complete milliseconds since the start of the second as three decimal digits.
Z
is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression HH:mm
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes “date-time” forms that consist of one of the above date-only forms immediately followed by one of the following time forms with an optional time zone offset appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
All numbers must be base 10. If the MM or DD fields are absent "01" is used as the value. If the HH, mm, or ss fields are absent "00" is used as the value and the value of an absent sss field is "000". When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
Illegal values (out-of-bounds as well as syntax errors) in a format string means that the format string is not a valid instance of this format.
Note 1
As every day both starts and ends with midnight, the two notations 00:00 and 24:00 are available to distinguish the two midnights that can be associated with one date. This means that the following two notations refer to exactly the same point in time: 1995-02-04T24:00 and 1995-02-05T00:00
Note 2
There exists no international standard that specifies abbreviations for civil time zones like CET, EST, etc. and sometimes the same abbreviation is even used for two very different time zones. For this reason, ISO 8601 and this format specifies numeric representations of date and time.
20.3.1.15.1Extended Years
ES requires the ability to specify 6 digit years (extended years); approximately 285,426 years, either forward or backward, from 01 January, 1970 UTC. To represent years before 0 or after 9999, ISO 8601 permits the expansion of the year representation, but only by prior agreement between the sender and the receiver. In the simplified ES format such an expanded year representation shall have 2 extra year digits and is always prefixed with a + or - sign. The year 0 is considered positive and hence prefixed with a + sign.
Note
Examples of extended years:
-283457-03-21T15:00:59.008Z
283458 B.C.
-000001-01-01T00:00:00Z
2 B.C.
+000000-01-01T00:00:00Z
1 B.C.
+000001-01-01T00:00:00Z
1 A.D.
+001970-01-01T00:00:00Z
1970 A.D.
+002009-12-15T00:00:00Z
2009 A.D.
+287396-10-12T08:59:00.992Z
287396 A.D.
20.3.2Date 构造器
The Date 构造器 is the %Date% 内部对象 and the 初始值 of the Date property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 Date object. When Date 被作为一个函数调用而不是一个 构造器, it returns a String representing the current time (UTC).
The Date构造器 is a single function whose behaviour is overloaded based upon the number and types of its arguments.
The Date构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 Date behaviour must include a super call to the Date构造器 以便创建和初始化子类实例 with a [[DateValue]] 内部属性.
Let tv be the result of parsing v as a date, in exactly the same manner as for the parse method (20.3.3.2). If the parse resulted in an abrupt completion, tv is the 完成记录.
The now function returns a Number 值 that is the time value designating the UTC date and time of the occurrence of the call to now.
20.3.3.2Date.parse ( string )
The parse function applies the ToString 运算符 to its argument. If ToString results in an abrupt completion the 完成记录 is immediately returned. Otherwise, parse interprets the resulting String as a date and time; it returns a Number, the UTC time value corresponding to the date and time. The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.15). If the String does not conform to that format the function may fall back to any 实现-specific heuristics or 实现-specific date formats. Unrecognizable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.
If x is any Date object whose milliseconds amount is zero within a particular 实现 of ES, then all of the following expressions should produce the same 数字值 in that 实现, if all the properties referenced have their initial values:
is not required to produce the same Number 值 as the preceding three expressions and, in general, the value produced by Date.parse is 实现-dependent when given any String 值 that does not conform to the Date Time String Format (20.3.1.15) and that could not be produced in that 实现 by the toString or toUTCString method.
The UTC function differs from the Date构造器 in two ways: it returns a time value as a Number, rather than creating a Date object, and it interprets the arguments in UTC rather than as local time.
20.3.4日期原型对象的属性
The Date 原型对象 is the 内部对象 %DatePrototype%. The Date 原型对象 is itself an 普通对象. It is not a Date instance and does not have a [[DateValue]] 内部属性.
[[Prototype]] 内部属性的值 of the Date 原型对象 is the 内部对象 %ObjectPrototype%.
Unless explicitly defined otherwise, the methods of the Date 原型对象 defined below are not generic and the this value passed to them must be an object that has a [[DateValue]] 内部属性 that has been initialized to a time value.
The 抽象操作 thisTimeValue(value) 执行如下:
If Type(value) is Object and value has a [[DateValue]] 内部属性, then
Return value.[[DateValue]].
抛出一个 TypeError 异常.
In following descriptions of functions that are 日期原型对象的属性, the phrase “this Date object” refers to the object that is the this value for the invocation of the function. If the Type of the this value is not Object, a TypeError 异常 is thrown. The phrase “this time value” within the specification of a method refers to the result returned by calling the 抽象操作 thisTimeValue with the this value of the method invocation passed as the argument.
20.3.4.1Date.prototype.constructor
The 初始值 of Date.prototype.constructor is the 内部对象 %Date%.
The length property of the setFullYear method is 3.
Note
If month is not present, this method behaves as if month was present with the value getMonth(). If date is not present, it behaves as if date was present with the value getDate().
20.3.4.22Date.prototype.setHours ( hour [ , min [ , sec [ , ms ] ] ] )
If min is not present, this method behaves as if min was present with the value getMinutes(). If sec is not present, it behaves as if sec was present with the value getSeconds(). If ms is not present, it behaves as if ms was present with the value getMilliseconds().
The length property of the setMinutes method is 3.
Note
If sec is not present, this method behaves as if sec was present with the value getSeconds(). If ms is not present, this behaves as if ms was present with the value getMilliseconds().
20.3.4.25Date.prototype.setMonth ( month [ , date ] )
The length property of the setUTCFullYear method is 3.
Note
If month is not present, this method behaves as if month was present with the value getUTCMonth(). If date is not present, it behaves as if date was present with the value getUTCDate().
20.3.4.30Date.prototype.setUTCHours ( hour [ , min [ , sec [ , ms ] ] ] )
The length property of the setUTCHours method is 4.
Note
If min is not present, this method behaves as if min was present with the value getUTCMinutes(). If sec is not present, it behaves as if sec was present with the value getUTCSeconds(). If ms is not present, it behaves as if ms was present with the value getUTCMilliseconds().
The length property of the setUTCMinutes method is 3.
Note
If sec is not present, this method behaves as if sec was present with the value getUTCSeconds(). If ms is not present, it function behaves as if ms was present with the value return by getUTCMilliseconds().
20.3.4.33Date.prototype.setUTCMonth ( month [ , date ] )
This function returns a String 值 representing the instance in time corresponding to this time value. The format of the String is the Date Time string format defined in 20.3.1.15. All fields are present in the String. The time zone is always UTC, denoted by the suffix Z. If this time value is not a finite Number or if the year is not a value that can be represented in that format (if necessary using extended year format), a RangeError 异常 is thrown.
20.3.4.37Date.prototype.toJSON ( key )
This function provides a String representation of a Date object for use by JSON.stringify (24.5.2).
When the toJSON method is called with argument key, 执行如下:
The toJSON function 是故意通用的; 不需要 its this value be a Date object. Therefore, 它可以转换为其它对象类型的方法而被使用. However, it does require that any such object have a toISOString method.
An ES 实现 that includes the ECMA-402 Internationalization API must implement the Date.prototype.toLocaleDateString method as specified in the ECMA-402 specification. If an ES 实现 does not include the ECMA-402 API the following specification of the toLocaleDateString method is used.
This function returns a String 值. The contents of the String are 实现-dependent, but are intended to represent the “date” portion of the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment's current locale.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
An ES 实现 that includes the ECMA-402 Internationalization API must implement the Date.prototype.toLocaleString method as specified in the ECMA-402 specification. If an ES 实现 does not include the ECMA-402 API the following specification of the toLocaleString method is used.
This function returns a String 值. The contents of the String are 实现-dependent, but are intended to represent the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment's current locale.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
An ES 实现 that includes the ECMA-402 Internationalization API must implement the Date.prototype.toLocaleTimeString method as specified in the ECMA-402 specification. If an ES 实现 does not include the ECMA-402 API the following specification of the toLocaleTimeString method is used.
This function returns a String 值. The contents of the String are 实现-dependent, but are intended to represent the “time” portion of the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment's current locale.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
If offset ≥ 0, let offsetSign be "+"; otherwise, let offsetSign be "-".
Let offsetMin be the String representation of MinFromTime(abs(offset)), formatted as a two-digit number, padded to the left with a zero if necessary.
Let offsetHour be the String representation of HourFromTime(abs(offset)), formatted as a two-digit number, padded to the left with a zero if necessary.
Let tzName be an 实现-defined string that is either the empty string or the string-concatenation of the 代码单元 0x0020 (SPACE), the 代码单元 0x0028 (LEFT PARENTHESIS), an 实现-dependent timezone name, and the 代码单元 0x0029 (RIGHT PARENTHESIS).
Return the string-concatenation of offsetSign, offsetHour, offsetMin, and tzName.
Let day be the String representation of DateFromTime(tv), formatted as a two-digit number, padded to the left with a zero if necessary.
Let year be the String representation of YearFromTime(tv), formatted as a number of at least four digits, padded to the left with zeroes if necessary.
Return the string-concatenation of weekday, ",", the 代码单元 0x0020 (SPACE), day, the 代码单元 0x0020 (SPACE), month, the 代码单元 0x0020 (SPACE), year, the 代码单元 0x0020 (SPACE), and TimeString(tv).
20.3.4.45Date.prototype [ @@toPrimitive ] ( hint )
This function is called by ES language operators to convert a Date object to a 原始值. The allowed values for hint are "default", "number", and "string". 日期对象, are unique among 内置 ES object in that they treat "default" as being equivalent to "string", All other 内置 ES 对象 treat "default" as being equivalent to "number".
When the @@toPrimitive method is called with argument hint, 执行如下:
Date 实例是从 Date 原型对象上继承属性的普通对象。Date 实例也有 [[DateValue]] 内部属性。[[DateValue]] 内部属性是由 this Date 对象表示的时间值。
21文本处理
21.1字符串对象
21.1.1String 构造器
The String 构造器 is the %String% 内部对象 and the 初始值 of the String property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 String 对象. When String 被作为一个函数调用而不是一个 构造器, 它会执行一个类型转换.
The String构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 String behaviour must include a super call to the String构造器 以便创建和初始化子类实例 with a [[StringData]] 内部属性.
The String.raw 函数可以以可变数量的参数的形式被调用. The first argument is template and the remainder of the arguments form the Listsubstitutions. 执行如下:
Let substitutions be a List consisting of all of the arguments passed to this function, starting with the second argument. If fewer than two arguments were passed, the List is empty.
Let numberOfSubstitutions be the number of elements in substitutions.
Append in order the 代码单元 elements of nextSub to the end of stringElements.
Let nextIndex be nextIndex + 1.
Note
String.raw is intended for use as a tag function of a Tagged Template (12.3.7). When called as such, the first argument will be a well formed template object and the rest parameter will contain the substitution values.
21.1.3String 原型对象的属性
The String 原型对象 is the 内部对象 %StringPrototype%. The String 原型对象 is a String 外来对象 and has the 内部方法 specified for such objects. It has a [[StringData]] 内部属性 with the value "". It has a length property whose 初始值 is 0 and whose 特性 are { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
[[Prototype]] 内部属性的值 of the String 原型对象 is the 内部对象 %ObjectPrototype%.
除非显式说明, the methods of the String 原型对象 defined below are not generic and the this value passed to them 必须是一个字符值或一个对象 that has a [[StringData]] 内部属性 that 已经被初始化为一个字符值.
返回一个单一元素字符串 containing the 代码单元 at index pos within the String 值 resulting from converting this object to a String. 如果该索引处没有元素, 那么结果是一个空字符串. 结果是一个 String 值, 而不是一个 String 对象.
If pos 是一个 Number 类型的整数值, then the result of x.charAt(pos) is equal to the result of x.substring(pos, pos+1).
When the charAt method is called with one argument pos, 执行如下:
If position < 0 or position ≥ size, return the empty String.
Return the String 值 of length 1, containing one 代码单元 from S, namely the 代码单元 at index position.
Note 2
The charAt function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.2String.prototype.charCodeAt ( pos )
Note 1
Returns a Number (一个非负整数 less than 216) that is the 数字值 of the 代码单元 at index pos within the String resulting from converting this object to a String. 如果该索引处没有元素, the result is NaN.
When the charCodeAt method is called with one argument pos, 执行如下:
Return a value of Number 类型, whose value is the 数字值 of the 代码单元 at index position within the String S.
Note 2
The charCodeAt function 是故意通用的; 不需要 its this value be a String 对象. Therefore 它可以转换为其它对象类型的方法而被使用.
21.1.3.3String.prototype.codePointAt ( pos )
Note 1
Returns 一个非负整数 Number less than 0x110000 that 是 UTF-16 编码码点的码点值 (6.1.4) starting at the string element at index pos within the String resulting from converting this object to a String. 如果该索引处没有元素, the result is undefined. 如果一个有效的 UTF-16 代理对没有 begin at pos, the result is the 代码单元 at pos.
When the codePointAt method is called with one argument pos, 执行如下:
If the sequence of elements of S starting at start of length searchLength is the same as the full element sequence of searchStr, return true.
Otherwise, return false.
Note 1
Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at endPosition - length(this). Otherwise returns false.
Note 2
Throwing an 异常 if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.
Note 3
The endsWith function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.7String.prototype.includes ( searchString [ , position ] )
The includes method takes two arguments, searchString and position, and 执行如下:
If there exists any integer k not smaller than start such that k + searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the 代码单元 at index k+j within S is the same as the 代码单元 at index j within searchStr, return true; but if there is no such integer k, return false.
Note 1
If searchString appears as a substring of the result of converting this object to a String, at one or more indices that are greater than or equal to position, return true; otherwise, returns false. If position is undefined, 0 is assumed, so as to search all of the String.
Note 2
Throwing an 异常 if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.
Note 3
The includes function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.8String.prototype.indexOf ( searchString [ , position ] )
Note 1
If searchString appears as a substring of the result of converting this object to a String, at one or more indices that are greater than or equal to position, then the smallest such index is returned; otherwise, -1 is returned. If position is undefined, 0 is assumed, so as to search all of the String.
The indexOf method takes two arguments, searchString and position, and 执行如下:
Return the smallest possible integer k not smaller than start such that k+searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the 代码单元 at index k+j within S is the same as the 代码单元 at index j within searchStr; but if there is no such integer k, return the value -1.
Note 2
The indexOf function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.9String.prototype.lastIndexOf ( searchString [ , position ] )
Note 1
If searchString appears as a substring of the result of converting this object to a String at one or more indices that are smaller than or equal to position, then the greatest such index is returned; otherwise, -1 is returned. If position is undefined, the length of the String 值 is assumed, so as to search all of the String.
The lastIndexOf method takes two arguments, searchString and position, and 执行如下:
Return the largest possible nonnegative integer k not larger than start such that k+searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the 代码单元 at index k+j within S is the same as the 代码单元 at index j within searchStr; but if there is no such integer k, return the value -1.
Note 2
The lastIndexOf function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
An ES 实现 that includes the ECMA-402 Internationalization API must implement the localeCompare method as specified in the ECMA-402 specification. If an ES 实现 does not include the ECMA-402 API the following specification of the localeCompare method is used.
When the localeCompare method is called with argument that, it returns a Number other than NaN that represents the result of a locale-sensitive String comparison of the this value (converted to a String) with that (converted to a String). The two Strings are S and That. The two Strings are compared in an 实现-defined fashion. The result is intended to order String values in the sort order specified by a host default locale, and will be negative, zero, or positive, depending on whether S comes before That in the sort order, the Strings are equal, or S comes after That in the sort order, respectively.
Before performing the comparisons, the following steps are performed to prepare the Strings:
The meaning of the optional second and third parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not assign any other interpretation to those parameter positions.
The localeCompare method, if considered as a function of two arguments this and that, is a consistent comparison function (as defined in 22.1.3.25) on the set of all Strings.
The actual return values are 实现-defined to permit implementers to encode additional information in the value, but the function is required to define a total ordering on all Strings. This function must treat Strings that are canonically equivalent according to the Unicode standard as identical and must return 0 when comparing Strings that are considered canonically equivalent.
Note 1
The localeCompare method itself is not directly suitable as an argument to Array.prototype.sort because the latter requires a function of two arguments.
Note 2
This function is intended to rely on whatever language-sensitive comparison functionality is available to the ES environment from the host environment, and to compare according to the rules of the host environment's current locale. However, regardless of the host provided comparison capabilities, this function must treat Strings that are canonically equivalent according to the Unicode standard as identical. It is recommended that this function should not honour Unicode compatibility equivalences or decompositions. For a definition and discussion of canonical equivalence see the Unicode Standard, chapters 2 and 3, as well as Unicode Standard Annex #15, Unicode Normalization Forms (https://unicode.org/reports/tr15/) and Unicode Technical Note #5, Canonical Equivalence in Applications (https://www.unicode.org/notes/tn5/). Also see Unicode Technical Standard #10, Unicode Collation 算法 (https://unicode.org/reports/tr10/).
Note 3
The localeCompare function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.11String.prototype.match ( regexp )
When the match method is called with argument regexp, 执行如下:
Search string for the first occurrence of searchString and let pos be the index within string of the first 代码单元 of the matched substring and let matched be searchString. If no occurrences of searchString were found, return string.
If functionalReplace is true, then
Let replValue be ? Call(replaceValue, undefined, « matched, pos, string »).
Let replStr be GetSubstitution(matched, string, pos, captures, undefined, replaceValue).
Let tailPos be pos + the number of 代码单元 in matched.
Let newString be the string-concatenation of the first pos 代码单元 of string, replStr, and the trailing substring of string starting at index tailPos. If pos is 0, the first element of the concatenation will be the empty String.
Return newString.
Note
The replace function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
Let result be the String 值 derived from replacement by copying 代码单元 elements from replacement to result while performing replacements as specified in Table 48. These $ replacements are done left-to-right, and, once such a replacement is performed, the new replacement text is not subject to further replacements.
Return result.
Table 48: Replacement Text Symbol Substitutions
代码单元
Unicode Characters
Replacement text
0x0024, 0x0024
$$
$
0x0024, 0x0026
$&
matched
0x0024, 0x0060
$`
If position is 0, the replacement is the empty String. Otherwise the replacement is the substring of str that starts at index 0 and whose last 代码单元 is at index position - 1.
0x0024, 0x0027
$'
If tailPos ≥ stringLength, the replacement is the empty String. Otherwise the replacement is the substring of str that starts at index tailPos and continues to the end of str.
0x0024, N
Where
0x0031 ≤ N ≤ 0x0039
$n where
n is one of 1 2 3 4 5 6 7 8 9 and $n is not followed by a decimal digit
The nth element of captures, where n is a single digit in the range 1 to 9. If n≤m and the nth element of captures is undefined, use the empty String instead. If n>m, no replacement is done.
0x0024, N, N
Where
0x0030 ≤ N ≤ 0x0039
$nn where
n is one of 0 1 2 3 4 5 6 7 8 9
The nnth element of captures, where nn is a two-digit decimal number in the range 01 to 99. If nn≤m and the nnth element of captures is undefined, use the empty String instead. If nn is 00 or nn>m, no replacement is done.
0x0024, 0x003C
$<
If namedCaptures is undefined, the replacement text is the String "$<".
Else,
Scan until the next > U+003E (GREATER-THAN SIGN).
If none is found, the replacement text is the String "$<".
The search function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.18String.prototype.slice ( start, end )
The slice method takes two arguments, start and end, and returns a substring of the result of converting this object to a String, starting from index start and running to, but not including, index end (or through the end of the String if end is undefined). If start is negative, it is treated as sourceLength+start where sourceLength is the length of the String. If end is negative, it is treated as sourceLength+end where sourceLength is the length of the String. 结果是一个 String 值, 而不是一个 String 对象. 执行如下:
Returns an Array object into which substrings of the result of converting this object to a String have been stored. The substrings are determined by searching from left to right for occurrences of separator; these occurrences are not part of any substring in the returned array, but serve to divide up the String 值. The value of separator may be a String of any length or it may be an object, 例如 a RegExp, that has a @@split method.
The value of separator may be an empty String. In this case, separator does not match the empty substring at the beginning or end of the input String, nor does it match the empty substring at the end of the previous separator match. If separator is the empty String, the String is split up into individual 代码单元 elements; the length of the result array equals the length of the String, and each substring contains one 代码单元.
If the this object is (or converts to) the empty String, the result depends on whether separator can match the empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, which is the empty String.
If separator is undefined, then the result array contains just one String, which is the this value (converted to a String). If limit is not undefined, then the output array is truncated so that it contains no more than limit elements.
Note 2
The split function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.19.1运行时语义: SplitMatch ( S, q, R )
The 抽象操作 SplitMatch takes three parameters, a String S, an integer q, and a String R, and 执行如下 in order to return either false or the end index of a match:
If there exists an integer i between 0 (inclusive) and r (exclusive) such that the 代码单元 at index q+i within S is different from the 代码单元 at index i within R, return false.
Return q+r.
21.1.3.20String.prototype.startsWith ( searchString [ , position ] )
If searchLength+start is greater than len, return false.
If the sequence of elements of S starting at start of length searchLength is the same as the full element sequence of searchStr, return true.
Otherwise, return false.
Note 1
This method returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at index position. Otherwise returns false.
Note 2
Throwing an 异常 if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.
Note 3
The startsWith function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.21String.prototype.substring ( start, end )
The substring method takes two arguments, start and end, and returns a substring of the result of converting this object to a String, starting from index start and running to, but not including, index end of the String (or through the end of the String if end is undefined). 结果是一个 String 值, 而不是一个 String 对象.
If either argument is NaN or negative, it is replaced with zero; if either argument is larger than the length of the String, it is replaced with the length of the String.
An ES 实现 that includes the ECMA-402 Internationalization API must implement the toLocaleLowerCase method as specified in the ECMA-402 specification. If an ES 实现 does not include the ECMA-402 API the following specification of the toLocaleLowerCase method is used.
This function interprets a String 值 as a sequence of UTF-16 encoded code points, as described in 6.1.4.
This function works exactly the same as toLowerCase except that its result is intended to yield the correct result for the host environment's current locale, rather than a locale-independent result. There will only be a difference in the few cases (例如 Turkish) where the rules for that language conflict with the regular Unicode case mappings.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
Note
The toLocaleLowerCase function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
An ES 实现 that includes the ECMA-402 Internationalization API must implement the toLocaleUpperCase method as specified in the ECMA-402 specification. If an ES 实现 does not include the ECMA-402 API the following specification of the toLocaleUpperCase method is used.
This function interprets a String 值 as a sequence of UTF-16 encoded code points, as described in 6.1.4.
This function works exactly the same as toUpperCase except that its result is intended to yield the correct result for the host environment's current locale, rather than a locale-independent result. There will only be a difference in the few cases (例如 Turkish) where the rules for that language conflict with the regular Unicode case mappings.
The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
Note
The toLocaleUpperCase function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.24String.prototype.toLowerCase ( )
This function interprets a String 值 as a sequence of UTF-16 encoded code points, as described in 6.1.4. 执行如下:
Let cpList be a List containing in order the code points as defined in 6.1.4 of S, starting at the first element of S.
Let cuList be a List where the elements are the result of toLowercase(cplist), according to the Unicode Default Case Conversion 算法.
Let L be the String 值 whose elements are the UTF16Encoding of the code points of cuList.
Return L.
The result must be derived according to the locale-insensitive case mappings in the Unicode Character Database (this explicitly includes not only the UnicodeData.txt file, but also all locale-insensitive mappings in the SpecialCasings.txt file that accompanies it).
Note 1
The case mapping of some code points may produce multiple code points. In this case the result String may not be the same length as the source String. Because both toUpperCase and toLowerCase have context-sensitive behaviour, the functions are not symmetrical. In other words, s.toUpperCase().toLowerCase() is not necessarily equal to s.toLowerCase().
Note 2
The toLowerCase function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
For a String 对象, the toString method happens to return the same thing as the valueOf method.
21.1.3.26String.prototype.toUpperCase ( )
This function interprets a String 值 as a sequence of UTF-16 encoded code points, as described in 6.1.4.
This function behaves in exactly the same way as String.prototype.toLowerCase, except that the String is mapped using the toUppercase 算法 of the Unicode Default Case Conversion.
Note
The toUpperCase function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
21.1.3.27String.prototype.trim ( )
This function interprets a String 值 as a sequence of UTF-16 encoded code points, as described in 6.1.4.
Let T be the String 值 that is a copy of S with both leading and trailing 空白 removed. The definition of 空白 is the union of WhiteSpace and LineTerminator. When determining whether a Unicode 码点 is in Unicode general category “Space_Separator” (“Zs”), 代码单元 sequences are interpreted as UTF-16 encoded 码点 sequences as specified in 6.1.4.
Return T.
Note
The trim function 是故意通用的; 不需要 its this value be a String 对象. Therefore, 它可以转换为其它对象类型的方法而被使用.
When the @@迭代器 method is called it returns an 迭代器 object (25.1.1.2) that iterates over the code points of a String 值, returning each 码点 as a String 值. 执行如下:
The value of the name property of this function is "[Symbol.迭代器]".
21.1.4String 实例的属性
String 实例 are String 外来对象 and have the 内部方法 specified for such objects. String 实例 继承属性 from the String 原型对象. String 实例 also have a [[StringData]] 内部属性.
String 实例 have a length property, 和一套带有整数索引名的可枚举属性.
String 迭代器是一个对象, that represents a specific iteration over some specific String instance object. There is not a named 构造器 for String 迭代器对象. Instead, String 迭代器对象 are created by calling certain methods of String instance objects.
21.1.5.1CreateStringIterator ( string )
Several methods of 字符串对象 return 迭代器对象. The 抽象操作 CreateStringIterator with argument string is used to create such 迭代器对象. It 执行如下:
All String 迭代器对象 继承属性 from the %StringIteratorPrototype% 内部对象. The %StringIteratorPrototype% object is an 普通对象 and its [[Prototype]] 内部属性 is the %IteratorPrototype% 内部对象. In addition, %StringIteratorPrototype% 有以下属性:
这是一个句法错误如果 IsCharacterClass of the first ClassAtom is true or IsCharacterClass of the second ClassAtom is true.
这是一个句法错误如果 IsCharacterClass of the first ClassAtom is false and IsCharacterClass of the second ClassAtom is false and the 字符值 of the first ClassAtom is larger than the 字符值 of the second ClassAtom.
这是一个句法错误如果 the List of Unicode code points that is 源文本 of UnicodePropertyName is not identical to a List of Unicode code points that is a Unicode 属性名 or property alias listed in the “属性名 and aliases” column of Table 51.
这是一个句法错误如果 the List of Unicode code points that is 源文本 of UnicodePropertyValue is not identical to a List of Unicode code points that is a value or value alias for the Unicode property or property alias given by 源文本 of UnicodePropertyName listed in the “Property value and aliases” column of the corresponding tables Table 53 or Table 54.
这是一个句法错误如果 the List of Unicode code points that is 源文本 of LoneUnicodePropertyNameOrValue is not identical to a List of Unicode code points that is a Unicode general category or general category alias listed in the “Property value and aliases” column of Table 53, nor a binary property or binary property alias listed in the “属性名 and aliases” column of Table 52.
正则表达式模式 is converted into an internal procedure using the process described below. An 实现 is encouraged to use more efficient 算法 than the ones listed below, as long as the results are the same. The internal procedure is used as the value of a RegExp 对象's [[RegExpMatcher]] 内部属性.
A Pattern is either a BMP pattern or a Unicode pattern depending upon whether or not its associated flags contain a "u". A BMP pattern matches against a String interpreted as consisting of a sequence of 16-bit values that are Unicode code points in the range of the Basic Multilingual Plane. A Unicode pattern matches against a String interpreted as consisting of Unicode code points encoded using UTF-16. In the context of describing the behaviour of a BMP pattern “character” means a single 16-bit Unicode BMP 码点. In the context of describing the behaviour of a Unicode pattern “character” means a UTF-16 encoded 码点 (6.1.4). In either context, “character value” means the 数字值 of the corresponding non-encoded 码点.
The syntax and 语义 of Pattern is defined as if the source code for the Pattern was a List of SourceCharacter values where each SourceCharacter corresponds to a Unicode 码点. If a BMP pattern contains a non-BMP SourceCharacter the entire pattern is encoded using UTF-16 and the individual 代码单元 of that encoding are used as the elements of the List.
Note
例如, consider a pattern expressed in 源文本 as the single non-BMP character U+1D11E (MUSICAL SYMBOL G CLEF). Interpreted as a Unicode pattern, it would be a single element (character) List consisting of the single 码点 0x1D11E. However, interpreted as a BMP pattern, it is first UTF-16 encoded to produce a two element List consisting of the 代码单元 0xD834 and 0xDD1E.
模式 are passed to the RegExp 构造器 as ES String values in which non-BMP characters are UTF-16 encoded. 例如, the single character MUSICAL SYMBOL G CLEF pattern, expressed as a String 值, is a String of length 2 whose elements were the 代码单元 0xD834 and 0xDD1E. So no further translation of the string would be necessary to process it as a BMP pattern consisting of two pattern characters. However, to process it as a Unicode pattern UTF16Decode must be used in producing a List consisting of a single pattern character, the 码点 U+1D11E.
An 实现 may not actually perform such translations to or from UTF-16, but the 语义 of this specification requires that the result of pattern matching be as if such translations were performed.
21.2.2.1Notation
The descriptions below use the following variables:
Input is a List consisting of all of the characters, in order, of the String being matched by the 正则表达式 pattern. Each character is either a 代码单元 or a 码点, depending upon the kind of pattern involved. The notation Input[n] means the nth character of Input, where n can range between 0 (inclusive) and InputLength (exclusive).
InputLength is the number of characters in Input.
NcapturingParens is the total number of left-capturing parentheses (i.e. the total number of Atom::(GroupSpecifierDisjunction) 解析节点) in the pattern. A left-capturing parenthesis is any ( pattern character that is matched by the ( terminal of the Atom::(GroupSpecifierDisjunction) production.
DotAll is true if the RegExp 对象's [[OriginalFlags]] 内部属性 contains "s" and otherwise is false.
IgnoreCase is true if the RegExp 对象's [[OriginalFlags]] 内部属性 contains "i" and otherwise is false.
Multiline is true if the RegExp 对象's [[OriginalFlags]] 内部属性 contains "m" and otherwise is false.
Unicode is true if the RegExp 对象's [[OriginalFlags]] 内部属性 contains "u" and otherwise is false.
Furthermore, the descriptions below use the following internal 数据结构:
A CharSet is a mathematical set of characters, either 代码单元 or code points depending up the state of the Unicode flag. “All characters” means either all 代码单元 values or all 码点 values also depending upon the state if Unicode.
A State is an ordered pair (endIndex, captures) where endIndex is an integer and captures is a List of NcapturingParens values. States are used to represent partial match states in the 正则表达式 matching 算法. The endIndex is one plus the index of the last input character matched so far by the pattern, while captures holds the results of capturing parentheses. The nth element of captures is either a List that represents the value obtained by the nth set of capturing parentheses or undefined if the nth set of capturing parentheses hasn't been reached yet. Due to backtracking, many States may be in use at any time during the matching process.
A MatchResult is either a State or the special token failure that indicates that the match failed.
A Continuation procedure is an internal closure (i.e. an internal procedure with some arguments already bound to values) that takes one State argument and returns a MatchResult result. If an internal closure references variables which are bound in the function that creates the closure, the closure uses the values that these variables had at the time the closure was created. The Continuation attempts to match the remaining portion (specified by the closure's already-bound arguments) of the pattern against Input, starting at the intermediate state given by its State argument. If the match succeeds, the Continuation returns the final State that it reached; if the match fails, the Continuation returns failure.
A Matcher procedure is an internal closure that takes two arguments — a State and a Continuation — and returns a MatchResult result. A Matcher attempts to match a middle subpattern (specified by the closure's already-bound arguments) of the pattern against Input, starting at the intermediate state given by its State argument. The Continuation argument should be a closure that matches the rest of the pattern. After matching the subpattern of a pattern to obtain a new State, the Matcher then calls Continuation on that new State to test if the rest of the pattern can match as well. If it can, the Matcher returns the State returned by Continuation; if not, the Matcher may try different choices at its choice points, repeatedly calling Continuation until it either succeeds or all possibilities have been exhausted.
An AssertionTester procedure is an internal closure that takes a State argument and returns a Boolean result. The assertion tester tests a specific condition (specified by the closure's already-bound arguments) against the current place in Input and returns true if the condition matched or false if not.
If Unicode is true, let Input be a List consisting of the sequence of code points of str interpreted as a UTF-16 encoded (6.1.4) Unicode string. Otherwise, let Input be a List consisting of the sequence of 代码单元 that are the elements of str. Input will be used throughout the 算法 in 21.2.2. Each element of Input is considered to be a character.
Let InputLength be the number of characters contained in Input. This variable will be used throughout the 算法 in 21.2.2.
Let listIndex be the index into Input of the character that was obtained from element index of str.
Let c be a Continuation that always returns its State argument as a successful MatchResult.
Let cap be a List of NcapturingParensundefined values, indexed 1 through NcapturingParens.
Let x be the State (listIndex, cap).
Call m(x, c) and return its result.
Note
A Pattern evaluates (“compiles”) to an internal procedure value. RegExpBuiltinExec can then apply this procedure to a String and an offset within the String to determine whether the pattern would match starting at exactly that offset within the String, and, if it does match, what the values of the capturing parentheses would be. The 算法 in 21.2.2 are designed so that compiling a pattern may 抛出一个 SyntaxError 异常; on the other hand, once the pattern is successfully compiled, applying the resulting internal procedure to find a match in a String cannot 抛出一个异常 (except for any host-defined exceptions that can occur anywhere 例如 out-of-memory).
Evaluate Alternative with argument direction to obtain a Matcher m1.
Evaluate Disjunction with argument direction to obtain a Matcher m2.
Return an internal Matcher closure that takes two arguments, a State x and a Continuation c, and 执行如下 when evaluated:
Call m1(x, c) and let r be its result.
If r is not failure, return r.
Call m2(x, c) and return its result.
Note
The | 正则表达式 运算符 separates two alternatives. The pattern first tries to match the left Alternative (followed by the sequel of the 正则表达式); if it fails, it tries to match the right Disjunction (followed by the sequel of the 正则表达式). If the left Alternative, the right Disjunction, and the sequel all have choice points, all choices in the sequel are tried before moving on to the next choice in the left Alternative. If choices in the left Alternative are exhausted, the right Disjunction is tried instead of the left Alternative. Any capturing parentheses inside a portion of the pattern skipped by | produce undefined values instead of Strings. Thus, 例如,
Return an internal Matcher closure that takes two arguments, a State x and a Continuation c, and 执行如下 when evaluated:
Let d be a Continuation that takes a State argument y and returns the result of calling m1(y, c).
Call m2(x, d) and return its result.
Note
Consecutive Terms try to simultaneously match consecutive portions of Input. When direction is equal to +1, if the left Alternative, the right Term, and the sequel of the 正则表达式 all have choice points, all choices in the sequel are tried before moving on to the next choice in the right Term, and all choices in the right Term are tried before moving on to the next choice in the left Alternative. When direction is equal to -1, the 估值 order of Alternative and Term are reversed.
21.2.2.5Term
With parameter direction.
The production Term::Assertion evaluates as follows:
Return an internal Matcher closure that takes two arguments, a State x and a Continuation c, and 执行如下 when evaluated:
Evaluate Assertion to obtain an AssertionTester t.
Evaluate Atom with argument direction to obtain a Matcher m.
Evaluate Quantifier to obtain the three results: an integer min, an integer (or ∞) max, and Boolean greedy.
Assert: If max is finite, then max is not less than min.
Let parenIndex be the number of left-capturing parentheses in the entire 正则表达式 that occur to the left of this Term. This is the total number of Atom::(GroupSpecifierDisjunction) 解析节点 prior to or enclosing this Term.
Let parenCount be the number of left-capturing parentheses in Atom. This is the total number of Atom::(GroupSpecifierDisjunction) 解析节点 enclosed by Atom.
Return an internal Matcher closure that takes two arguments, a State x and a Continuation c, and 执行如下 when evaluated:
Call RepeatMatcher(m, min, max, greedy, x, c, parenIndex, parenCount) and return its result.
The 抽象操作 RepeatMatcher takes eight parameters, a Matcher m, an integer min, an integer (or ∞) max, a Boolean greedy, a State x, a Continuation c, an integer parenIndex, and an integer parenCount, and 执行如下:
If max is zero, return c(x).
Let d be an internal Continuation closure that takes one State argument y and 执行如下 when evaluated:
If min is zero and y's endIndex is equal to x's endIndex, return failure.
If min is zero, let min2 be zero; otherwise let min2 be min-1.
If max is ∞, let max2 be ∞; otherwise let max2 be max-1.
Call RepeatMatcher(m, min2, max2, greedy, y, c, parenIndex, parenCount) and return its result.
For each integer k that satisfies parenIndex < k and k ≤ parenIndex+parenCount, set cap[k] to undefined.
Let e be x's endIndex.
Let xr be the State (e, cap).
If min is not zero, return m(xr, d).
If greedy is false, then
Call c(x) and let z be its result.
If z is not failure, return z.
Call m(xr, d) and return its result.
Call m(xr, d) and let z be its result.
If z is not failure, return z.
Call c(x) and return its result.
Note 1
An Atom followed by a Quantifier is repeated the number of times specified by the Quantifier. A Quantifier can be non-greedy, in which case the Atom pattern is repeated as few times as possible while still matching the sequel, or it can be greedy, in which case the Atom pattern is repeated as many times as possible while still matching the sequel. The Atom pattern is repeated rather than the input character sequence that it matches, so different repetitions of the Atom can match different input substrings.
Note 2
If the Atom and the sequel of the 正则表达式 all have choice points, the Atom is first matched as many (or as few, if non-greedy) times as possible. All choices in the sequel are tried before moving on to the next choice in the last repetition of Atom. All choices in the last (nth) repetition of Atom are tried before moving on to the next choice in the next-to-last (n-1)st repetition of Atom; at which point it may turn out that more or fewer repetitions of Atom are now possible; these are exhausted (again, starting with either as few or as many as possible) before moving on to the next choice in the (n-1)st repetition of Atom and so on.
Compare
/a[a-z]{2,4}/.exec("abcdefghi")
which returns "abcde" with
/a[a-z]{2,4}?/.exec("abcdefghi")
which returns "abc".
Consider also
/(aa|aabaac|ba|b|c)*/.exec("aabaac")
which, by the choice point ordering above, returns the array
["aaba", "ba"]
and not any of:
["aabaac", "aabaac"]
["aabaac", "c"]
The above ordering of choice points can be used to write a 正则表达式 that calculates the greatest common divisor of two numbers (represented in 一元 notation). The following example calculates the gcd of 10 and 15:
Step 4 of the RepeatMatcher clears Atom's captures each time Atom is repeated. We can see its behaviour in the 正则表达式
/(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")
which returns the array
["zaacbbbcac", "z", "ac", "a", undefined, "c"]
and not
["zaacbbbcac", "z", "ac", "a", "bbb", "c"]
because each iteration of the outermost * clears all captured Strings contained in the quantified Atom, which in this case includes capture Strings numbered 2, 3, 4, and 5.
Note 4
Step 1 of the RepeatMatcher's d closure states that, once the minimum number of repetitions has been satisfied, any more expansions of Atom that match the empty character sequence are not considered for further repetitions. This prevents the 正则表达式 engine from falling into an infinite loop on 模式 例如:
Evaluate Disjunction with argument direction to obtain a Matcher m.
Let parenIndex be the number of left-capturing parentheses in the entire 正则表达式 that occur to the left of this Atom. This is the total number of Atom::(GroupSpecifierDisjunction) 解析节点 prior to or enclosing this Atom.
Return an internal Matcher closure that takes two arguments, a State x and a Continuation c, and 执行如下:
Let d be an internal Continuation closure that takes one State argument y and 执行如下:
The 抽象操作 Canonicalize takes a character parameter ch and 执行如下:
If IgnoreCase is false, return ch.
If Unicode is true, then
If the file CaseFolding.txt of the Unicode Character Database provides a simple or common case folding mapping for ch, return the result of applying that mapping to ch.
If u does not consist of a single 代码单元, return ch.
Let cu be u's single 代码单元 element.
If the 数字值 of ch ≥ 128 and the 数字值 of cu < 128, return ch.
Return cu.
Note 1
Parentheses of the form (Disjunction) serve both to group the components of the Disjunction pattern together and to save the result of the match. The result can be used either in a backreference (\ followed by a nonzero decimal number), referenced in a replace String, or returned as part of an array from the 正则表达式 matching internal procedure. To inhibit the capturing behaviour of parentheses, use the form (?:Disjunction) instead.
Note 2
The form (?=Disjunction) specifies a zero-width positive lookahead. In order for it to succeed, the pattern inside Disjunction must match at the current position, but the current position is not advanced before matching the sequel. If Disjunction can match at the current position in several ways, only the first one is tried. Unlike other 正则表达式 operators, there is no backtracking into a (?= form (this unusual behaviour is inherited from Perl). This only matters when the Disjunction contains capturing parentheses and the sequel of the pattern contains backreferences to those captures.
例如,
/(?=(a+))/.exec("baaabac")
matches the empty String immediately after the first b and therefore returns the array:
["", "aaa"]
To illustrate the lack of backtracking into the lookahead, consider:
/(?=(a+))a*b\1/.exec("baaabac")
This expression returns
["aba", "a"]
and not:
["aaaba", "a"]
Note 3
The form (?!Disjunction) specifies a zero-width negative lookahead. In order for it to succeed, the pattern inside Disjunction must fail to match at the current position. The current position is not advanced before matching the sequel. Disjunction can contain capturing parentheses, but backreferences to them only make sense from within Disjunction itself. Backreferences to these capturing parentheses from elsewhere in the pattern always return undefined because the negative lookahead must fail for the pattern to succeed. 例如,
/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac")
looks for an a not immediately followed by some positive number n of a's, a b, another n a's (specified by the first \2) and a c. The second \2 is outside the negative lookahead, so it matches against undefined and therefore always succeeds. The whole expression returns the array:
["baaabaac", "ba", undefined, "abaac"]
Note 4
In case-insignificant matches when Unicode is true, all characters are implicitly case-folded using the simple mapping provided by the Unicode standard immediately before they are compared. The simple mapping always maps to a single 码点, so it does not map, 例如, "ß" (U+00DF) to "SS". It may however map a 码点 outside the Basic Latin range to a character within, 例如, "ſ" (U+017F) to "s". Such characters are not mapped if Unicode is false. This prevents Unicode code points 例如 U+017F and U+212A from matching 正则表达式 例如 /[a-z]/i, but they will match /[a-z]/ui.
21.2.2.8.3运行时语义: UnicodeMatchProperty ( p )
The 抽象操作 UnicodeMatchProperty takes a parameter p that is a List of Unicode code points and 执行如下:
Assert: p is a List of Unicode code points that is identical to a List of Unicode code points that is a Unicode 属性名 or property alias listed in the “属性名 and aliases” column of Table 51 or Table 52.
Let c be the canonical 属性名 of p as given in the “Canonical 属性名” column of the corresponding row.
Implementations must support the Unicode property names and aliases listed in Table 51 and Table 52. To ensure interoperability, implementations must not support any other property names or aliases.
Note 1
例如, Script_Extensions (属性名) and scx (property alias) are valid, but script_extensions or Scx aren't.
Note 2
The listed properties form a superset of what UTS18 RL1.2 requires.
Table 51: Non-binary Unicode property aliases and their canonical property names
21.2.2.8.4运行时语义: UnicodeMatchPropertyValue ( p, v )
The 抽象操作 UnicodeMatchPropertyValue takes two parameters p and v, each of which is a List of Unicode code points, and 执行如下:
Assert: p is a List of Unicode code points that is identical to a List of Unicode code points that is a canonical, unaliased Unicode 属性名 listed in the “Canonical 属性名” column of Table 51.
Assert: v is a List of Unicode code points that is identical to a List of Unicode code points that is a property value or property value alias for Unicode property p listed in the “Property value and aliases” column of Table 53 or Table 54.
Let value be the canonical property value of v as given in the “Canonical property value” column of the corresponding row.
Implementations must support the Unicode property value names and aliases listed in Table 53 and Table 54. To ensure interoperability, implementations must not support any other property value names or aliases.
Note 1
例如, Xpeo and Old_Persian are valid Script_Extension values, but xpeo and Old Persian aren't.
Call CharacterSetMatcher(A, false, direction) and return its Matcher result.
Note
An escape sequence of the form \ followed by a nonzero decimal number n matches the result of the nth set of capturing parentheses (21.2.2.1). It is an error if the 正则表达式 has fewer than n capturing parentheses. If the 正则表达式 has n or more capturing parentheses but the nth one is undefined because it has not captured anything, then the backreference always succeeds.
Let parenIndex be the number of left-capturing parentheses in the entire 正则表达式 that occur to the left of the located GroupSpecifier. This is the total number of Atom::(GroupSpecifierDisjunction) 解析节点 prior to or enclosing the located GroupSpecifier.
If there exists an integer i between 0 (inclusive) and len (exclusive) such that Canonicalize(s[i]) is not the same character value as Canonicalize(Input[g + i]), return failure.
If \ is followed by a decimal number n whose first digit is not 0, then the escape sequence is considered to be a backreference. It is an error if n is greater than the total number of left-capturing parentheses in the entire 正则表达式.
If ! UnicodeMatchPropertyValue("General_Category", s) is identical to a List of Unicode code points that is the name of a Unicode general category or general category alias listed in the “Property value and aliases” column of Table 53, then
Return the CharSet containing all Unicode code points whose character database definition includes the property “General_Category” with value s.
Call CharacterRange(A, B) and let D be the resulting CharSet.
Return the union of CharSets D and C.
Note 1
ClassRanges can expand into a single ClassAtom and/or ranges of two ClassAtom separated by dashes. In the latter case the ClassRanges includes all characters between the first ClassAtom and the second ClassAtom, inclusive; an error occurs if either ClassAtom does not represent a single character (例如, if one is \w) or if the first ClassAtom's character value is greater than the second ClassAtom's character value.
Note 2
Even if the pattern ignores case, the case of the two ends of a range is significant in determining which characters belong to the range. Thus, 例如, the pattern /[E-F]/i matches only the letters E, F, e, and f, while the pattern /[E-f]/i matches all upper and lower-case letters in the Unicode Basic Latin block as well as the symbols [, \, ], ^, _, and `.
Note 3
A - character can be treated literally or it can denote a range. It is treated literally if it is the first or last character of ClassRanges, the beginning or end limit of a range specification, or immediately follows a range specification.
A ClassAtom can use any of the escape sequences that are allowed in the rest of the 正则表达式 except for \b, \B, and backreferences. Inside a CharacterClass, \b means the backspace character, while \B and backreferences raise errors. Using a backreference inside a ClassAtom causes an error.
21.2.3RegExp 构造器
The RegExp 构造器 is the %RegExp% 内部对象 and the 初始值 of the RegExp property of the 全局对象. When RegExp 被作为一个函数调用而不是一个 构造器, 它会创建和初始化一个新的 RegExp 对象. Thus the function call RegExp(…) is equivalent to the object creation expression new RegExp(…) with the same arguments.
The RegExp构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 RegExp behaviour must include a super call to the RegExp构造器 to create and initialize subclass instances with the necessary 内部属性.
If pattern is supplied using a StringLiteral, the usual escape sequence substitutions are performed before the String is processed by RegExp. If pattern must contain an escape sequence to be recognized by RegExp, any U+005C (REVERSE SOLIDUS) code points must be escaped within the StringLiteral to prevent them being removed when the contents of the StringLiteral are formed.
21.2.3.2RegExp 构造器的抽象操作
21.2.3.2.1运行时语义: RegExpAlloc ( newTarget )
When the 抽象操作 RegExpAlloc with argument newTarget is called, 执行如下:
Let obj be ? OrdinaryCreateFromConstructor(newTarget, "%RegExpPrototype%", « [[RegExpMatcher]], [[OriginalSource]], [[OriginalFlags]] »).
If F contains any 代码单元 other than "g", "i", "m", "s", "u", or "y" or if it contains the same 代码单元 more than once, 抛出一个 SyntaxError 异常.
If F contains "u", let BMP be false; else let BMP be true.
If BMP is true, then
Parse P using the grammars in 21.2.1 and interpreting each of its 16-bit elements as a Unicode BMP 码点. UTF-16 decoding is not applied to the elements. The 目标符 for the parse is Pattern[~U, ~N]. If the result of parsing contains a GroupName, reparse with the 目标符Pattern[~U, +N] and use this result instead. 抛出一个 SyntaxError 异常 if P did not conform to the grammar, if any elements of P were not matched by the parse, or if any 早期错误 conditions exist.
Let patternCharacters be a List whose elements are the 代码单元 elements of P.
Else,
Parse P using the grammars in 21.2.1 and interpreting P as UTF-16 encoded Unicode code points (6.1.4). The 目标符 for the parse is Pattern[+U, +N]. 抛出一个 SyntaxError 异常 if P did not conform to the grammar, if any elements of P were not matched by the parse, or if any 早期错误 conditions exist.
Let patternCharacters be a List whose elements are the code points resulting from applying UTF-16 decoding to P's sequence of elements.
Set obj.[[OriginalSource]] to P.
Set obj.[[OriginalFlags]] to F.
Set obj.[[RegExpMatcher]] to the internal procedure that evaluates the above parse of P by applying the 语义 provided in 21.2.2 using patternCharacters as the pattern's List of SourceCharacter values and F as the flag parameters.
When the 抽象操作 EscapeRegExpPattern with arguments P and F is called, the following occurs:
Let S be a String in the form of a Pattern[~U] (Pattern[+U] if F contains "u") equivalent to P interpreted as UTF-16 encoded Unicode code points (6.1.4), in which certain code points are escaped as described below. S may or may not be identical to P; however, the internal procedure that would result from evaluating S as a Pattern[~U] (Pattern[+U] if F contains "u") must behave identically to the internal procedure given by the constructed object's [[RegExpMatcher]] 内部属性. Multiple calls to this 抽象操作 using the same values for P and F must produce identical results.
The code points / or any LineTerminator occurring in the pattern shall be escaped in S as necessary to ensure that the string-concatenation of "/", S, "/", and F can be parsed (in an appropriate lexical context) as a RegularExpressionLiteral that behaves identically to the constructed 正则表达式. 例如, if P is "/", then S could be "\/" or "\u002F", among other possibilities, but not "/", because /// followed by F would be parsed as a SingleLineComment rather than a RegularExpressionLiteral. If P is the empty String, this specification can be met by letting S be "(?:)".
RegExp[@@species] is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Return the this value.
The value of the name property of this function is "get [Symbol.species]".
Note
RegExp prototype methods normally use their this object's 构造器 to create a derived object. However, a subclass 构造器 may over-ride that default behaviour by redefining its @@species property.
21.2.5RegExp 原型对象的属性
The RegExp 原型对象 is the 内部对象 %RegExpPrototype%. The RegExp 原型对象 is an 普通对象. It is not a RegExp instance and does not have a [[RegExpMatcher]] 内部属性 or any of the other 内部属性 of RegExp instance objects.
[[Prototype]] 内部属性的值 of the RegExp 原型对象 is the 内部对象 %ObjectPrototype%.
Note
The RegExp 原型对象 does not have a valueOf property of its own; however, it inherits the valueOf property from the Object 原型对象.
21.2.5.1RegExp.prototype.constructor
The 初始值 of RegExp.prototype.constructor is the 内部对象 %RegExp%.
21.2.5.2RegExp.prototype.exec ( string )
Performs a 正则表达式 match of string against the 正则表达式 and returns an Array object containing the results of the match, or null if string did not match.
The String ToString(string) is searched for an occurrence of the 正则表达式 pattern as follows:
If a callable exec property is not found this 算法 falls back to attempting to use the 内置 RegExp matching 算法. This provides compatible behaviour for code written for prior editions where most 内置 算法 that use 正则表达式 did not perform a dynamic property lookup of exec.
21.2.5.2.2运行时语义: RegExpBuiltinExec ( R, S )
The 抽象操作 RegExpBuiltinExec with arguments R and S 执行如下:
e is an index into the Input character list, derived from S, matched by matcher. Let eUTF be the smallest index into S that corresponds to the character at element e of Input. If e is greater than or equal to the number of elements in Input, then eUTF is the number of 代码单元 in S.
The value of the name property of this function is "[Symbol.match]".
Note
The @@match property is used by the IsRegExp 抽象操作 to identify objects that have the basic behaviour of 正则表达式. The absence of a @@match property or the existence of such a property whose value does not Boolean coerce to true indicates that the object is not intended to be used as a 正则表达式 object.
21.2.5.8get RegExp.prototype.multiline
RegExp.prototype.multiline is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Let replacement be GetSubstitution(matched, S, position, captures, namedCaptures, replaceValue).
If position ≥ nextSourcePosition, then
NOTE: position should not normally move backwards. If it does, it is an indication of an ill-behaving RegExp subclass or use of an access triggered side-effect to change the global flag or other characteristics of rx. In such cases, the corresponding substitution is ignored.
Let accumulatedResult be the string-concatenation of the current value of accumulatedResult, the substring of S consisting of the 代码单元 from nextSourcePosition (inclusive) up to position (exclusive), and replacement.
Let nextSourcePosition be position + matchLength.
If nextSourcePosition ≥ lengthS, return accumulatedResult.
Return the string-concatenation of accumulatedResult and the substring of S consisting of the 代码单元 from nextSourcePosition (inclusive) up through the final 代码单元 of S (inclusive).
The value of the name property of this function is "[Symbol.replace]".
21.2.5.10RegExp.prototype [ @@search ] ( string )
When the @@search method is called with argument string, 执行如下:
Returns an Array object into which substrings of the result of converting string to a String have been stored. The substrings are determined by searching from left to right for matches of the this value 正则表达式; these occurrences are not part of any substring in the returned array, but serve to divide up the String 值.
The this value may be an empty 正则表达式 or a 正则表达式 that can match an empty String. In this case, the 正则表达式 does not match the empty substring at the beginning or end of the input String, nor does it match the empty substring at the end of the previous separator match. (例如, if the 正则表达式 matches the empty String, the String is split up into individual 代码单元 elements; the length of the result array equals the length of the String, and each substring contains one 代码单元.) Only the first match at a given index of the String is considered, even if backtracking could yield a non-empty-substring match at that index. (例如, /a*?/[Symbol.split]("ab") evaluates to the array ["a","b"], while /a*/[Symbol.split]("ab") evaluates to the array ["","b"].)
If the string is (or converts to) the empty String, the result depends on whether the 正则表达式 can match the empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, which is the empty String.
If the 正则表达式 contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array. 例如,
If flags contains the 代码单元 0x0075 (LATIN SMALL LETTER U), return true.
Return false.
21.2.6RegExp 实例的属性
RegExp instances are 普通对象 that 继承属性 from the RegExp 原型对象. RegExp instances have 内部属性 [[RegExpMatcher]], [[OriginalSource]], and [[OriginalFlags]]. The value of the [[RegExpMatcher]] 内部属性 is an 实现-dependent representation of the Pattern of the RegExp 对象.
Note
Prior to ES 2015, RegExp instances were specified as having the own data properties source, global, ignoreCase, and multiline. Those properties are now specified as 访问器属性 of RegExp.prototype.
RegExp instances also have the following property:
21.2.6.1lastIndex
The value of the lastIndex property specifies the String index at which to start the next match. It is coerced to an integer when used (see 21.2.5.2.2). This property shall have the 特性 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.
22索引集合
22.1Array 对象
Array 对象 are 外来对象 that give special treatment to a certain class of property names. See 9.4.2 for a definition of this special treatment.
22.1.1Array 构造器
The Array 构造器 is the %Array% 内部对象 and the 初始值 of the Array property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 Array 外来对象. When Array 被作为一个函数调用而不是一个 构造器, it also creates and initializes a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.
The Array构造器 is a single function whose behaviour is overloaded based upon the number and types of its arguments.
The Array构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that intend to inherit the exotic Array behaviour must include a super call to the Array构造器 to initialize subclass instances that are Array 外来对象. However, most of the Array.prototype methods are generic methods that are not dependent upon their this value being an Array 外来对象.
The length property of the Array构造器 function is 1.
22.1.1.1Array ( )
This description applies if and only if the Array 构造器 is called with no arguments.
Let numberOfArgs be the number of arguments passed to this function call.
The from function is an intentionally generic factory method; 不需要 its this value be the Array 构造器. Therefore it can be transferred to or inherited by any other constructors that may be called with a single numeric argument.
22.1.2.2Array.isArray ( arg )
The isArray function takes one argument arg, and 执行如下:
The items argument is assumed to be a well-formed rest argument value.
Note 2
The of function is an intentionally generic factory method; 不需要 its this value be the Array 构造器. Therefore it can be transferred to or inherited by other constructors that may be called with a single numeric argument.
22.1.2.4Array.prototype
The value of Array.prototype is %ArrayPrototype%, the intrinsic Array 原型对象.
Array[@@species] is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Return the this value.
The value of the name property of this function is "get [Symbol.species]".
Note
Array prototype methods normally use their this object's 构造器 to create a derived object. However, a subclass 构造器 may over-ride that default behaviour by redefining its @@species property.
22.1.3Array 原型对象的属性
The Array 原型对象 is the 内部对象 %ArrayPrototype%. The Array 原型对象 is an Array 外来对象 and has the 内部方法 specified for such objects. It has a length property whose 初始值 is 0 and whose 特性 are { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.
[[Prototype]] 内部属性的值 of the Array 原型对象 is the 内部对象 %ObjectPrototype%.
Note
The Array 原型对象 is specified to be an Array 外来对象 to ensure compatibility with ES 代码 that was created prior to the ES 2015 specification.
22.1.3.1Array.prototype.concat ( ...arguments )
When the concat 方法以零个或多个参数的形式被调用, it returns an array containing the array elements of the object followed by the array elements of each argument in order.
Let items be a List whose first element is O and whose subsequent elements are, in left to right order, the arguments that were passed to this function invocation.
Repeat, while items is not empty
Remove the first element from items and let E be the value of the element.
The explicit setting of the length property in step 6 is necessary to ensure that its value is correct in situations where the trailing elements of the result Array are not present.
Note 2
The concat function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
The 初始值 of Array.prototype.constructor is the 内部对象 %Array%.
22.1.3.3Array.prototype.copyWithin ( target, start [ , end ] )
The copyWithin method takes up to three arguments target, start and end.
Note 1
The end argument is optional with the length of the this object as its 默认值. If target is negative, it is treated as length+target where length is the length of the array. If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean 值 true or false. every calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns false. If such an element is found, every immediately returns false. Otherwise, if callbackfn returned true for all elements, every will return true. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not provided, undefined is used instead.
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
every does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by every is set before the first call to callbackfn. Elements which are appended to the array after the call to every begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time every visits them; elements that are deleted after the call to every begins and before being visited are not visited. every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true.
When the every method is called with one or two arguments, 执行如下:
Let testResult be ToBoolean(? Call(callbackfn, T, « kValue, k, O »)).
If testResult is false, return false.
Increase k by 1.
Return true.
Note 2
The every function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
22.1.3.6Array.prototype.fill ( value [ , start [ , end ] ] )
The fill method takes up to three arguments value, start and end.
Note 1
The start and end arguments are optional with default values of 0 and the length of the this object. If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end.
callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean 值 true or false. filter calls callbackfn once for each element in the array, in ascending order, and constructs a new array of all the values for which callbackfn returns true. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not provided, undefined is used instead.
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
filter does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by filter is set before the first call to callbackfn. Elements which are appended to the array after the call to filter begins will not be visited by callbackfn. If existing elements of the array are changed their value as passed to callbackfn will be the value at the time filter visits them; elements that are deleted after the call to filter begins and before being visited are not visited.
When the filter method is called with one or two arguments, 执行如下:
The find method is called with one or two arguments, predicate and thisArg.
Note 1
predicate should be a function that accepts three arguments and returns a value that is coercible to a Boolean 值. find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
If a thisArg parameter is provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
predicate is called with three arguments: the value of the element, the index of the element, and the object being traversed.
find does not directly mutate the object on which it is called but the object may be mutated by the calls to predicate.
The range of elements processed by find is set before the first call to predicate. Elements that are appended to the array after the call to find begins will not be visited by predicate. If existing elements of the array are changed, their value as passed to predicate will be the value at the time that find visits them.
predicate should be a function that accepts three arguments and returns a value that is coercible to the Boolean 值 true or false. findIndex calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns the index of that element value. Otherwise, findIndex returns -1.
If a thisArg parameter is provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
predicate is called with three arguments: the value of the element, the index of the element, and the object being traversed.
findIndex does not directly mutate the object on which it is called but the object may be mutated by the calls to predicate.
The range of elements processed by findIndex is set before the first call to predicate. Elements that are appended to the array after the call to findIndex begins will not be visited by predicate. If existing elements of the array are changed, their value as passed to predicate will be the value at the time that findIndex visits them.
When the findIndex method is called with one or two arguments, 执行如下:
callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each element present in the array, in ascending order. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not provided, undefined is used instead.
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
When the forEach method is called with one or two arguments, 执行如下:
includes compares searchElement to the elements of the array, in ascending order, using the SameValueZero 算法, and if found at any position, returns true; otherwise, false is returned.
The optional second argument fromIndex defaults to 0 (i.e. the whole array is searched). If it is greater than or equal to the length of the array, false is returned, i.e. the array will not be searched. If it is negative, it is used as the offset from the end of the array to compute fromIndex. If the computed index is less than 0, the whole array will be searched.
Let n be ? ToInteger(fromIndex). (If fromIndex is undefined, this step produces the value 0.)
If n ≥ 0, then
Let k be n.
Else n < 0,
Let k be len + n.
If k < 0, let k be 0.
Repeat, while k < len
Let elementK be the result of ? Get(O, ! ToString(k)).
If SameValueZero(searchElement, elementK) is true, return true.
Increase k by 1.
Return false.
Note 2
The includes function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
Note 3
The includes method intentionally differs from the similar indexOf method in two ways. First, it uses the SameValueZero 算法, instead of 严格相等比较, allowing it to detect NaN array elements. Second, it does not skip missing array elements, instead treating them as undefined.
indexOf compares searchElement to the elements of the array, in ascending order, using the 严格相等比较 算法, and if found at one or more indices, returns the smallest such index; otherwise, -1 is returned.
The optional second argument fromIndex defaults to 0 (i.e. the whole array is searched). If it is greater than or equal to the length of the array, -1 is returned, i.e. the array will not be searched. If it is negative, it is used as the offset from the end of the array to compute fromIndex. If the computed index is less than 0, the whole array will be searched.
When the indexOf method is called with one or two arguments, 执行如下:
Let same be the result of performing 严格相等比较searchElement === elementK.
If same is true, return k.
Increase k by 1.
Return -1.
Note 2
The indexOf function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
22.1.3.13Array.prototype.join ( separator )
Note 1
The elements of the array are converted to Strings, and these Strings are then concatenated, separated by occurrences of the separator. If no separator is provided, a single comma is used as the separator.
The join method takes one argument, separator, and 执行如下:
lastIndexOf compares searchElement to the elements of the array in descending order using the 严格相等比较 算法, and if found at one or more indices, returns the largest such index; otherwise, -1 is returned.
The optional second argument fromIndex defaults to the array's length minus one (i.e. the whole array is searched). If it is greater than or equal to the length of the array, the whole array will be searched. If it is negative, it is used as the offset from the end of the array to compute fromIndex. If the computed index is less than 0, -1 is returned.
When the lastIndexOf method is called with one or two arguments, 执行如下:
callbackfn should be a function that accepts three arguments. map calls callbackfn once for each element in the array, in ascending order, and constructs a new Array from the results. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not provided, undefined is used instead.
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
map does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by map is set before the first call to callbackfn. Elements which are appended to the array after the call to map begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time map visits them; elements that are deleted after the call to map begins and before being visited are not visited.
When the map method is called with one or two arguments, 执行如下:
The pop function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
22.1.3.18Array.prototype.push ( ...items )
Note 1
The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.
callbackfn should be a function that takes four arguments. reduce calls the callback, as a function, once for each element after the first element present in the array, in ascending order.
callbackfn is called with four arguments: the previousValue (value from the previous call to callbackfn), the currentValue (value of the current element), the currentIndex, and the object being traversed. The first time that callback is called, the previousValue and currentValue can be one of two values. If an initialValue was supplied in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was supplied, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. It is a TypeError if the array contains no elements and initialValue is not provided.
reduce does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by reduce is set before the first call to callbackfn. Elements that are appended to the array after the call to reduce begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time reduce visits them; elements that are deleted after the call to reduce begins and before being visited are not visited.
When the reduce method is called with one or two arguments, 执行如下:
callbackfn should be a function that takes four arguments. reduceRight calls the callback, as a function, once for each element after the first element present in the array, in descending order.
callbackfn is called with four arguments: the previousValue (value from the previous call to callbackfn), the currentValue (value of the current element), the currentIndex, and the object being traversed. The first time the function is called, the previousValue and currentValue can be one of two values. If an initialValue was supplied in the call to reduceRight, then previousValue will be equal to initialValue and currentValue will be equal to the last value in the array. If no initialValue was supplied, then previousValue will be equal to the last value in the array and currentValue will be equal to the second-to-last value. It is a TypeError if the array contains no elements and initialValue is not provided.
reduceRight does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by reduceRight is set before the first call to callbackfn. Elements that are appended to the array after the call to reduceRight begins will not be visited by callbackfn. If existing elements of the array are changed by callbackfn, their value as passed to callbackfn will be the value at the time reduceRight visits them; elements that are deleted after the call to reduceRight begins and before being visited are not visited.
When the reduceRight method is called with one or two arguments, 执行如下:
The shift function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
22.1.3.23Array.prototype.slice ( start, end )
Note 1
The slice method takes two arguments, start and end, and returns an array containing the elements of the array from element start up to, but not including, element end (or through the end of the array if end is undefined). If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end where length is the length of the array.
The explicit setting of the length property of the result Array in step 11 was necessary in previous editions of ES to ensure that its length was correct in situations where the trailing elements of the result Array were not present. Setting length became unnecessary starting in ES2015 when the result Array was initialized to its proper length rather than an empty Array but is carried forward to preserve backward compatibility.
Note 3
The slice function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean 值 true or false. some calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns true. If such an element is found, some immediately returns true. Otherwise, some returns false. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not provided, undefined is used instead.
callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.
some does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
The range of elements processed by some is set before the first call to callbackfn. Elements that are appended to the array after the call to some begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time that some visits them; elements that are deleted after the call to some begins and before being visited are not visited. some acts like the "exists" quantifier in mathematics. In particular, for an empty array, it returns false.
When the some method is called with one or two arguments, 执行如下:
Let testResult be ToBoolean(? Call(callbackfn, T, « kValue, k, O »)).
If testResult is true, return true.
Increase k by 1.
Return false.
Note 2
The some function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
22.1.3.25Array.prototype.sort ( comparefn )
The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.
Upon entry, the following steps are performed to initialize 估值 of the sort function:
If comparefn is not undefined and IsCallable(comparefn) is false, 抛出一个 TypeError 异常.
Within this specification of the sort method, an object, obj, is said to be sparse if the following 算法 returns true:
For each integer i in the range 0≤i< len, do
Let elem be obj.[[GetOwnProperty]](! ToString(i)).
If elem is undefined, return true.
Return false.
The sort order is the ordering, after completion of this function, of the integer-indexed property values of obj whose integer indexes are less than len. The result of the sort function is then determined as follows:
If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the sort order is 实现-defined. The sort order is also 实现-defined if comparefn is undefined and SortCompare does not act as a consistent comparison function.
Let proto be obj.[[GetPrototypeOf]](). If proto is not null and there exists an integer j such that all of the conditions below are satisfied then the sort order is 实现-defined:
Any 整数索引 property of obj whose name is 一个非负整数 less than len is a 数据属性 whose [[Configurable]] 特性 is false.
The sort order is also 实现-defined if any of the following conditions are true:
If obj is an 外来对象 (including Proxy 外来对象) whose behaviour for [[Get]], [[Set]], [[Delete]], and [[GetOwnProperty]] is not the 普通对象 实现 of these 内部方法.
If any index property of obj whose name is 一个非负整数 less than len is an 访问器属性 or is a 数据属性 whose [[Writable]] 特性 is false.
If comparefn is undefined and the application of ToString to any value passed as an argument to SortCompare modifies obj or any object on obj's prototype chain.
If comparefn is undefined and all applications of ToString, to any specific value passed as an argument to SortCompare, do not produce the same result.
执行如下:
Perform an 实现-dependent sequence of calls to the [[Get]] and [[Set]] 内部方法 of obj, to the DeletePropertyOrThrow and HasOwnProperty 抽象操作 with obj as the first argument, and to SortCompare (described below), such that:
The property key argument for each call to [[Get]], [[Set]], HasOwnProperty, or DeletePropertyOrThrow is the string representation of 一个非负整数 less than len.
The arguments for calls to SortCompare are values returned by a previous call to the [[Get]] 内部方法, unless the properties accessed by those previous calls did not exist according to HasOwnProperty. If both perspective arguments to SortCompare correspond to non-existent properties, use +0 instead of calling SortCompare. If only the first perspective argument is non-existent use +1. If only the second perspective argument is non-existent use -1.
If any [[Set]] call returns false a TypeError 异常 is thrown.
If an abrupt completion is returned from any of these operations, it is immediately returned as the value of this function.
Return obj.
Unless the sort order is specified above to be 实现-defined, the returned object must have the following two characteristics:
There must be some mathematical permutation π of the nonnegative integers less than len, such that for every nonnegative integer j less than len, if property old[j] existed, then new[π(j)] is exactly the same value as old[j]. But if property old[j] did not exist, then new[π(j)] does not exist.
Then for all nonnegative integers j and k, each less than len, if SortCompare(old[j], old[k]) < 0 (see SortCompare below), then new[π(j)] < new[π(k)].
Here the notation old[j] is used to refer to the hypothetical result of calling obj.[[Get]](j) before this function is executed, and the notation new[j] to refer to the hypothetical result of calling obj.[[Get]](j) after this function has been executed.
A function comparefn is a consistent comparison function for a set of values S if all of the requirements below are met for all values a, b, and c (possibly the same value) in the set S: The notation a <CFb means comparefn(a, b) < 0; a =CFb means comparefn(a, b) = 0 (of either sign); and a >CFb means comparefn(a, b) > 0.
Calling comparefn(a, b) always returns the same value v when given a specific pair of values a and b as its two arguments. Furthermore, Type(v) is Number, and v is not NaN. Note that this implies that exactly one of a <CFb, a =CFb, and a >CFb will be true for a given pair of a and b.
Calling comparefn(a, b) does not modify obj or any object on obj's prototype chain.
a =CFa (reflexivity)
If a =CFb, then b =CFa (symmetry)
If a =CFb and b =CFc, then a =CFc (transitivity of =CF)
If a <CFb and b <CFc, then a <CFc (transitivity of <CF)
If a >CFb and b >CFc, then a >CFc (transitivity of >CF)
Note 1
The above conditions are necessary and sufficient to ensure that comparefn divides the set S into equivalence classes and that these equivalence classes are totally ordered.
Note 2
The sort function 是故意通用的; 不需要 its this value be an Array object. Therefore, 它可以转换为其它对象类型的方法而被使用.
22.1.3.25.1运行时语义: SortCompare( x, y )
The SortCompare 抽象操作 is called with two arguments x and y. It also has access to the comparefn argument passed to the current invocation of the sort method. 执行如下:
If x and y are both undefined, return +0.
If x is undefined, return 1.
If y is undefined, return -1.
If comparefn is not undefined, then
Let v be ? ToNumber(? Call(comparefn, undefined, « x, y »)).
Let xSmaller be the result of performing 抽象关系比较xString < yString.
If xSmaller is true, return -1.
Let ySmaller be the result of performing 抽象关系比较yString < xString.
If ySmaller is true, return 1.
Return +0.
Note 1
Because non-existent property values always compare greater than undefined property values, and undefined always compares greater than any other value, undefined property values always sort to the end of the result, followed by non-existent property values.
Note 2
Method calls performed by the ToString抽象操作 in steps 5 and 7 have the potential to cause SortCompare to not behave as a consistent comparison function.
When the splice method is called with two or more arguments start, deleteCount and zero or more items, the deleteCount elements of the array starting at 整数索引start are replaced by the arguments items. An Array object containing the deleted elements (if any) is returned.
Let items be a List whose elements are, in left to right order, the portion of the actual argument list starting with the third argument. The list is empty if fewer than three arguments were passed.
Perform ? Set(O, "length", len - actualDeleteCount + itemCount, true).
Return A.
Note 2
The explicit setting of the length property of the result Array in step 19 was necessary in previous editions of ES to ensure that its length was correct in situations where the trailing elements of the result Array were not present. Setting length became unnecessary starting in ES2015 when the result Array was initialized to its proper length rather than an empty Array but is carried forward to preserve backward compatibility.
Note 3
The splice function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
An ES 实现 that includes the ECMA-402 Internationalization API must implement the Array.prototype.toLocaleString method as specified in the ECMA-402 specification. If an ES 实现 does not include the ECMA-402 API the following specification of the toLocaleString method is used.
Note 1
The first edition of ECMA-402 did not include a replacement specification for the Array.prototype.toLocaleString method.
The meanings of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.
Let separator be the String 值 for the list-separator String appropriate for the host environment's current locale (this is derived in an 实现-defined way).
The elements of the array are converted to Strings using their toLocaleString methods, and these Strings are then concatenated, separated by occurrences of a separator String that has been derived in an 实现-defined locale-specific way. The result of calling this function is intended to be analogous to the result of toString, except that the result of this function is intended to be locale-specific.
Note 3
The toLocaleString function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
The toString function 是故意通用的; 不需要 its this value be an Array object. Therefore 它可以转换为其它对象类型的方法而被使用.
22.1.3.29Array.prototype.unshift ( ...items )
Note 1
The arguments are prepended to the start of the array, such that their order within the array is the same as the order in which they appear in the argument list.
When the unshift 方法以零个或多个参数的形式被调用 item1, item2, etc., 执行如下:
The 自身属性 names of this object are property names that were not included as standard properties of Array.prototype prior to the ES 2015 specification. These names are ignored for with statement binding purposes in order to preserve the behaviour of existing code that might use one of these names as a binding in an outer scope that is shadowed by a with statement whose binding object is an Array object.
22.1.4Array 实例的属性
Array instances are Array 外来对象 and have the 内部方法 specified for such objects. Array instances 继承属性 from the Array 原型对象.
Array instances have a length property, and a set of enumerable properties with array index names.
22.1.4.1length
The length property of an Array instance is a 数据属性 whose value is always numerically greater than the name of every configurable 自身属性 whose name is an array index.
The length property initially has the 特性 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.
Note
Reducing the value of the length property has the side-effect of deleting own array elements whose array index is between the old and new length values. However, non-configurable properties can not be deleted. Attempting to set the length property of an Array object to a value that is numerically less than or equal to the largest numeric own 属性名 of an existing non-configurable array-indexed property of the array will result in the length being set to a 数字值 that is one greater than that non-configurable numeric own 属性名. See 9.4.2.1.
22.1.5Array 迭代器对象
An Array 迭代器 is an object, that represents a specific iteration over some specific Array instance object. There is not a named 构造器 for Array 迭代器对象. Instead, Array 迭代器对象 are created by calling certain methods of Array instance objects.
22.1.5.1CreateArrayIterator ( array, kind )
Several methods of Array 对象 return 迭代器对象. The 抽象操作 CreateArrayIterator with arguments array and kind is used to create such 迭代器对象. It 执行如下:
All Array 迭代器对象 继承属性 from the %ArrayIteratorPrototype% 内部对象. The %ArrayIteratorPrototype% object is an 普通对象 and its [[Prototype]] 内部属性 is the %IteratorPrototype% 内部对象. In addition, %ArrayIteratorPrototype% 有以下属性:
Array 迭代器实例 are 普通对象 that 继承属性 from the %ArrayIteratorPrototype% 内部对象. Array 迭代器实例 are initially created with the 内部属性 listed in Table 55.
Table 55: 内部属性 of Array 迭代器实例
内部属性
Description
[[IteratedObject]]
The object whose array elements are being iterated.
[[ArrayIteratorNextIndex]]
The 整数索引 of the next 整数索引 to be examined by this iteration.
[[ArrayIterationKind]]
A String 值 that identifies what is returned for each element of the iteration. The possible values are: "key", "value", "key+value".
22.2TypedArray 对象
TypedArray objects present an array-like view of an underlying binary data buffer (24.1). Each element of a TypedArray instance has the same underlying binary scalar data type. There is a distinct TypedArray构造器, listed in Table 56, for each of the nine supported element types. Each 构造器 in Table 56 has a corresponding distinct 原型对象.
In the definitions below, references to TypedArray should be replaced with the appropriate 构造器 name from the above table. The phrase “the element size in bytes” refers to the value in the Element Size column of the table in the row corresponding to the 构造器. The phrase “element Type” refers to the value in the Element Type column for that row.
22.2.1%TypedArray% 内部对象
The %TypedArray% 内部对象 is a 构造器函数对象 that all of the TypedArray构造器 objects inherit from. %TypedArray% and its corresponding 原型对象 provide common properties that are inherited by all TypedArray constructors and their instances. The %TypedArray% intrinsic does not have a global name or appear as a property of the 全局对象.
The %TypedArray% intrinsic 函数对象 acts as the abstract superclass of the various TypedArray constructors. Because it is an abstract class 构造器 it will throw an error when invoked. The TypedArray constructors do not perform a super call to it.
%TypedArray%[@@species] is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Return the this value.
The value of the name property of this function is "get [Symbol.species]".
Note
%TypedArrayPrototype% methods normally use their this object's 构造器 to create a derived object. However, a subclass 构造器 may over-ride that default behaviour by redefining its @@species property.
22.2.3Properties of the %TypedArrayPrototype% Object
[[Prototype]] 内部属性的值 of the %TypedArrayPrototype% object is the 内部对象 %ObjectPrototype%. The %TypedArrayPrototype% object is an 普通对象. It does not have a [[ViewedArrayBuffer]] or any other of the 内部属性 that are specific to TypedArray instance objects.
22.2.3.1get %TypedArray%.prototype.buffer
%TypedArray%.prototype.buffer is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
22.2.3.5%TypedArray%.prototype.copyWithin ( target, start [ , end ] )
The interpretation and use of the arguments of %TypedArray%.prototype.copyWithin are the same as for Array.prototype.copyWithin as defined in 22.1.3.3.
%TypedArray%.prototype.every is a distinct function that implements the same 算法 as Array.prototype.every as defined in 22.1.3.5 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法 and must take into account the possibility that calls to callbackfn may cause the this value to become detached.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
22.2.3.8%TypedArray%.prototype.fill ( value [ , start [ , end ] ] )
The interpretation and use of the arguments of %TypedArray%.prototype.fill are the same as for Array.prototype.fill as defined in 22.1.3.6.
%TypedArray%.prototype.find is a distinct function that implements the same 算法 as Array.prototype.find as defined in 22.1.3.8 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法 and must take into account the possibility that calls to predicate may cause the this value to become detached.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
%TypedArray%.prototype.findIndex is a distinct function that implements the same 算法 as Array.prototype.findIndex as defined in 22.1.3.9 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法 and must take into account the possibility that calls to predicate may cause the this value to become detached.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
%TypedArray%.prototype.forEach is a distinct function that implements the same 算法 as Array.prototype.forEach as defined in 22.1.3.10 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法 and must take into account the possibility that calls to callbackfn may cause the this value to become detached.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
%TypedArray%.prototype.includes is a distinct function that implements the same 算法 as Array.prototype.includes as defined in 22.1.3.11 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
%TypedArray%.prototype.indexOf is a distinct function that implements the same 算法 as Array.prototype.indexOf as defined in 22.1.3.12 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
%TypedArray%.prototype.join is a distinct function that implements the same 算法 as Array.prototype.join as defined in 22.1.3.13 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
%TypedArray%.prototype.lastIndexOf is a distinct function that implements the same 算法 as Array.prototype.lastIndexOf as defined in 22.1.3.15 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
22.2.3.18get %TypedArray%.prototype.length
%TypedArray%.prototype.length is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
%TypedArray%.prototype.reduce is a distinct function that implements the same 算法 as Array.prototype.reduce as defined in 22.1.3.19 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法 and must take into account the possibility that calls to callbackfn may cause the this value to become detached.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
%TypedArray%.prototype.reduceRight is a distinct function that implements the same 算法 as Array.prototype.reduceRight as defined in 22.1.3.20 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法 and must take into account the possibility that calls to callbackfn may cause the this value to become detached.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
22.2.3.22%TypedArray%.prototype.reverse ( )
%TypedArray%.prototype.reverse is a distinct function that implements the same 算法 as Array.prototype.reverse as defined in 22.1.3.21 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
Sets multiple values in this TypedArray, reading the values from the object array. The optional offset value indicates the first element index in this TypedArray where values are written. If omitted, it is assumed to be 0.
Assert: array is any ES 语言值 other than an Object with a [[TypedArrayName]] 内部属性. If it is such an Object, the definition in 22.2.3.23.2 applies.
Sets multiple values in this TypedArray, reading the values from the typedArray argument object. The optional offset value indicates the first element index in this TypedArray where values are written. If omitted, it is assumed to be 0.
Assert: typedArray has a [[TypedArrayName]] 内部属性. If it does not, the definition in 22.2.3.23.1 applies.
%TypedArray%.prototype.some is a distinct function that implements the same 算法 as Array.prototype.some as defined in 22.1.3.24 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法 and must take into account the possibility that calls to callbackfn may cause the this value to become detached.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
%TypedArray%.prototype.sort is a distinct function that, except as described below, implements the same requirements as those of Array.prototype.sort as defined in 22.1.3.25. The 实现 of the %TypedArray%.prototype.sort specification may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. The only 内部方法 of the this object that the 算法 may call are [[Get]] and [[Set]].
This function is not generic. The this value must be an object with a [[TypedArrayName]] 内部属性.
Upon entry, the following steps are performed to initialize 估值 of the sort function. These steps are used instead of the entry steps in 22.1.3.25:
If comparefn is not undefined and IsCallable(comparefn) is false, 抛出一个 TypeError 异常.
The 实现-defined sort order condition for 外来对象 is not applied by %TypedArray%.prototype.sort.
The following version of SortCompare is used by %TypedArray%.prototype.sort. It performs a numeric comparison rather than the string comparison used in 22.1.3.25. SortCompare has access to the comparefn and buffer values of the current invocation of the sort method.
When the TypedArray SortCompare 抽象操作 is called with two arguments x and y, 执行如下:
Because NaN always compares greater than any other value, NaN property values always sort to the end of the result when comparefn is not provided.
22.2.3.27%TypedArray%.prototype.subarray( begin, end )
Returns a new TypedArray object whose element type is the same as this TypedArray and whose ArrayBuffer is the same as the ArrayBuffer of this TypedArray, referencing the elements at begin, inclusive, up to end, exclusive. If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning.
%TypedArray%.prototype.toLocaleString is a distinct function that implements the same 算法 as Array.prototype.toLocaleString as defined in 22.1.3.27 except that the this object's [[ArrayLength]] 内部属性 is accessed in place of performing a [[Get]] of "length". The 实现 of the 算法 may be optimized with the knowledge that the this value is an object that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce any observable changes in the specified behaviour of the 算法.
This function is not generic. ValidateTypedArray is applied to the this value prior to evaluating the 算法. If its result is an abrupt completion that 异常 is thrown instead of evaluating the 算法.
Note
If the ES 实现 includes the ECMA-402 Internationalization API this function is based upon the 算法 for Array.prototype.toLocaleString that is in the ECMA-402 specification.
22.2.3.29%TypedArray%.prototype.toString ( )
The 初始值 of the %TypedArray%.prototype.toString数据属性 is the same 内置 函数对象 as the Array.prototype.toString method defined in 22.1.3.28.
The 初始值 of the name property of this function is "get [Symbol.toStringTag]".
22.2.4The TypedArray Constructors
Each of the TypedArray构造器 objects is an 内部对象 that has the structure described below, differing only in the name used as the 构造器 name instead of TypedArray, in Table 56.
The TypedArray intrinsic 构造器 functions are single functions whose behaviour is overloaded based upon the number and types of its arguments. The actual behaviour of a call of TypedArray depends upon the number and kind of arguments that are passed to it.
The TypedArray constructors are not intended to be called as a function and will 抛出一个异常 when called in that manner.
The TypedArray constructors are designed to be subclassable. They may be used as the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 TypedArray behaviour must include a super call to the TypedArray构造器 以便创建和初始化子类实例 with the 内部状态 necessary to support the %TypedArray%.prototype 内置方法.
The length property of the TypedArray构造器 function is 3.
22.2.4.1TypedArray ( )
This description applies only if the TypedArray function is called with no arguments.
If NewTarget is undefined, 抛出一个 TypeError 异常.
Let constructorName be the String 值 of the 构造器 Name value specified in Table 56 for this TypedArray构造器.
The 抽象操作 AllocateTypedArray with arguments constructorName, newTarget, defaultProto and 可选参数 length is used to validate and create an instance of a TypedArray 构造器. constructorName is required to be the name of a TypedArray 构造器 in Table 56. If the length argument is passed, an ArrayBuffer of that length is also allocated and associated with the new TypedArray instance. AllocateTypedArray provides common 语义 that is used by all of the TypedArray overloads. AllocateTypedArray 执行如下:
This description applies only if the TypedArray function is called with at least one argument and the Type of the first argument is Object and that object has a [[TypedArrayName]] 内部属性.
TypedArray called with argument typedArray 执行如下:
Assert: Type(typedArray) is Object and typedArray has a [[TypedArrayName]] 内部属性.
If NewTarget is undefined, 抛出一个 TypeError 异常.
Let constructorName be the String 值 of the 构造器 Name value specified in Table 56 for this TypedArray构造器.
Let O be ? AllocateTypedArray(constructorName, NewTarget, "%TypedArrayPrototype%").
Set srcByteIndex to srcByteIndex + srcElementSize.
Set targetByteIndex to targetByteIndex + elementSize.
Decrement count by 1.
Set O.[[ViewedArrayBuffer]] to data.
Set O.[[ByteLength]] to byteLength.
Set O.[[ByteOffset]] to 0.
Set O.[[ArrayLength]] to elementLength.
Return O.
22.2.4.4TypedArray ( object )
This description applies only if the TypedArray function is called with at least one argument and the Type of the first argument is Object and that object does not have either a [[TypedArrayName]] or an [[ArrayBufferData]] 内部属性.
TypedArray called with argument object 执行如下:
Assert: Type(object) is Object and object does not have either a [[TypedArrayName]] or an [[ArrayBufferData]] 内部属性.
If NewTarget is undefined, 抛出一个 TypeError 异常.
Let constructorName be the String 值 of the 构造器 Name value specified in Table 56 for this TypedArray构造器.
Let O be ? AllocateTypedArray(constructorName, NewTarget, "%TypedArrayPrototype%").
This description applies only if the TypedArray function is called with at least one argument and the Type of the first argument is Object and that object has an [[ArrayBufferData]] 内部属性.
TypedArray called with at least one argument buffer 执行如下:
Assert: Type(buffer) is Object and buffer has an [[ArrayBufferData]] 内部属性.
If NewTarget is undefined, 抛出一个 TypeError 异常.
Let constructorName be the String 值 of the 构造器 Name value specified in Table 56 for this TypedArray构造器.
Let O be ? AllocateTypedArray(constructorName, NewTarget, "%TypedArrayPrototype%").
Let elementSize be the Number 值 of the Element Size value in Table 56 for constructorName.
Let bufferByteLength be buffer.[[ArrayBufferByteLength]].
If length is either not present or undefined, then
If bufferByteLengthmoduloelementSize ≠ 0, 抛出一个 RangeError 异常.
Let newByteLength be bufferByteLength - offset.
If newByteLength < 0, 抛出一个 RangeError 异常.
Else,
Let newByteLength be newLength × elementSize.
If offset+newByteLength > bufferByteLength, 抛出一个 RangeError 异常.
Set O.[[ViewedArrayBuffer]] to buffer.
Set O.[[ByteLength]] to newByteLength.
Set O.[[ByteOffset]] to offset.
Set O.[[ArrayLength]] to newByteLength / elementSize.
Return O.
22.2.4.6TypedArrayCreate ( 构造器, argumentList )
The 抽象操作 TypedArrayCreate with arguments 构造器 and argumentList is used to specify the creation of a new TypedArray object using a 构造器 function. It 执行如下:
Let newTypedArray be ? Construct(构造器, argumentList).
The 抽象操作 TypedArraySpeciesCreate with arguments exemplar and argumentList is used to specify the creation of a new TypedArray object using a 构造器 function that is derived from exemplar. It 执行如下:
Assert: exemplar is an Object that has a [[TypedArrayName]] 内部属性.
Let defaultConstructor be the 内部对象 listed in column one of Table 56 for exemplar.[[TypedArrayName]].
[[Prototype]] 内部属性的值 of a TypedArray 原型对象 is the 内部对象 %TypedArrayPrototype%. A TypedArray 原型对象 is an 普通对象. It does not have a [[ViewedArrayBuffer]] or any other of the 内部属性 that are specific to TypedArray instance objects.
22.2.6.1TypedArray.prototype.BYTES_PER_ELEMENT
The value of TypedArray.prototype.BYTES_PER_ELEMENT is the Number 值 of the Element Size value specified in Table 56 for TypedArray.
The 初始值 of a TypedArray.prototype.constructor is the corresponding %TypedArray% 内部对象.
22.2.7Properties of TypedArray Instances
TypedArray instances are Integer-Indexed 外来对象. Each TypedArray instance inherits properties from the corresponding TypedArray 原型对象. Each TypedArray instance has the following 内部属性: [[TypedArrayName]], [[ViewedArrayBuffer]], [[ByteLength]], [[ByteOffset]], and [[ArrayLength]].
23键集合
23.1Map 对象
Map 对象 are collections of key/value pairs where both the keys and values may be arbitrary ES 语言值. A distinct key value may only occur in one key/value pair within the Map's collection. Distinct key values are discriminated using the SameValueZero 比较算法.
Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The 数据结构 used in this Map 对象 specification is only intended to describe the required observable 语义 of Map 对象. It is not intended to be a viable 实现 model.
23.1.1Map 构造器
The Map 构造器 is the %Map% 内部对象 and the 初始值 of the Map property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 Map object. Map is not intended to be called as a function and will 抛出一个异常 when called in that manner.
The Map构造器 被设计成可被子类化的. 它可以用作 the value in an extends clause of a class definition. 子类构造器 that 旨在继承特定的 Map behaviour must include a super call to the Map构造器 以便创建和初始化子类实例 with the 内部状态 necessary to support the Map.prototype 内置方法.
If the parameter iterable is present, it is expected to be an object that implements an @@迭代器 method that returns an 迭代器 object that produces a two element array-like object whose first element is a value that will be used as a Map key and whose second element is the value to associate with that key.
Map[@@species] is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Return the this value.
The value of the name property of this function is "get [Symbol.species]".
Note
Methods that create derived collection objects should call @@species to determine the 构造器 to use to create the derived objects. Subclass 构造器 may over-ride @@species to change the default 构造器 assignment.
23.1.3Map 原型对象的属性
The Map 原型对象 is the 内部对象 %MapPrototype%. [[Prototype]] 内部属性的值 of the Map 原型对象 is the 内部对象 %ObjectPrototype%. The Map 原型对象 is an 普通对象. It does not have a [[MapData]] 内部属性.
For each Record {[[Key]], [[Value]]} p that is an element of entries, do
If p.[[Key]] is not empty and SameValueZero(p.[[Key]], key) is true, then
Set p.[[Key]] to empty.
Set p.[[Value]] to empty.
Return true.
Return false.
Note
The value empty is used as a specification device to indicate that an entry has been deleted. Actual implementations may take other actions 例如 physically removing the entry from internal 数据结构.
For each Record {[[Key]], [[Value]]} e that is an element of entries, in original key insertion order, do
If e.[[Key]] is not empty, then
Perform ? Call(callbackfn, T, « e.[[Value]], e.[[Key]], M »).
Return undefined.
Note
callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each key/value pair present in the map object, in key insertion order. callbackfn is called only for keys of the map which actually exist; it is not called for keys that have been deleted from the map.
If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not provided, undefined is used instead.
callbackfn is called with three arguments: the value of the item, the key of the item, and the Map object being traversed.
forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn. Each entry of a map's [[MapData]] is only visited once. New keys added after the call to forEach begins are visited. A key will be revisited if it is deleted after it has been visited and then re-added before the forEach call completes. Keys that are deleted after the call to forEach begins and before being visited are not visited unless the key is added again before the forEach call completes.
Map instances are 普通对象 that 继承属性 from the Map prototype. Map instances also have a [[MapData]] 内部属性.
23.1.5Map 迭代器对象
A Map 迭代器 is an object, that represents a specific iteration over some specific Map instance object. There is not a named 构造器 for Map 迭代器对象. Instead, Map 迭代器对象 are created by calling certain methods of Map instance objects.
23.1.5.1CreateMapIterator ( map, kind )
Several methods of Map 对象 return 迭代器对象. The 抽象操作 CreateMapIterator with arguments map and kind is used to create such 迭代器对象. It 执行如下:
All Map 迭代器对象 继承属性 from the %MapIteratorPrototype% 内部对象. The %MapIteratorPrototype% 内部对象 is an 普通对象 and its [[Prototype]] 内部属性 is the %IteratorPrototype% 内部对象. In addition, %MapIteratorPrototype% 有以下属性:
Map 迭代器实例 are 普通对象 that 继承属性 from the %MapIteratorPrototype% 内部对象. Map 迭代器实例 are initially created with the 内部属性 described in Table 57.
Table 57: 内部属性 of Map 迭代器实例
内部属性
Description
[[Map]]
The Map object that is being iterated.
[[MapNextIndex]]
The 整数索引 of the next Map data element to be examined by this 迭代器.
[[MapIterationKind]]
A String 值 that identifies what is to be returned for each element of the iteration. The possible values are: "key", "value", "key+value".
23.2Set 对象
Set 对象 are collections of ES 语言值. A distinct value may only occur once as an element of a Set's collection. Distinct values are discriminated using the SameValueZero 比较算法.
Set 对象 must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The 数据结构 used in this Set 对象 specification is only intended to describe the required observable 语义 of Set 对象. It is not intended to be a viable 实现 model.
23.2.1Set 构造器
The Set 构造器 is the %Set% 内部对象 and the 初始值 of the Set property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 Set object. Set is not intended to be called as a function and will 抛出一个异常 when called in that manner.
The Set构造器 被设计成可被子类化的. 它可以用作 the value in an extends clause of a class definition. 子类构造器 that 旨在继承特定的 Set behaviour must include a super call to the Set构造器 以便创建和初始化子类实例 with the 内部状态 necessary to support the Set.prototype 内置方法.
23.2.1.1Set ( [ iterable ] )
When the Set function is called with 可选参数 iterable, 执行如下:
Set[@@species] is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Return the this value.
The value of the name property of this function is "get [Symbol.species]".
Note
Methods that create derived collection objects should call @@species to determine the 构造器 to use to create the derived objects. Subclass 构造器 may over-ride @@species to change the default 构造器 assignment.
23.2.3Set 原型对象的属性
The Set 原型对象 is the 内部对象 %SetPrototype%. [[Prototype]] 内部属性的值 of the Set 原型对象 is the 内部对象 %ObjectPrototype%. The Set 原型对象 is an 普通对象. It does not have a [[SetData]] 内部属性.
If e is not empty and SameValueZero(e, value) is true, then
Replace the element of entries whose value is e with an element whose value is empty.
Return true.
Return false.
Note
The value empty is used as a specification device to indicate that an entry has been deleted. Actual implementations may take other actions 例如 physically removing the entry from internal 数据结构.
callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each value present in the set object, in value insertion order. callbackfn is called only for values of the Set which actually exist; it is not called for keys that have been deleted from the set.
If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not provided, undefined is used instead.
callbackfn is called with three arguments: the first two arguments are a value contained in the Set. The same value is passed for both arguments. The Set object being traversed is passed as the third argument.
The callbackfn is called with three arguments to be consistent with the call back functions used by forEach methods for Map and Array. For Sets, each item value is considered to be both the key and the value.
forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.
Each value is normally visited only once. However, a value will be revisited if it is deleted after it has been visited and then re-added before the forEach call completes. Values that are deleted after the call to forEach begins and before being visited are not visited unless the value is added again before the forEach call completes. New values added after the call to forEach begins are visited.
Set instances are 普通对象 that 继承属性 from the Set prototype. Set instances also have a [[SetData]] 内部属性.
23.2.5Set 迭代器对象
A Set 迭代器 is an 普通对象, with the structure defined below, that represents a specific iteration over some specific Set instance object. There is not a named 构造器 for Set 迭代器对象. Instead, Set 迭代器对象 are created by calling certain methods of Set instance objects.
23.2.5.1CreateSetIterator ( set, kind )
Several methods of Set 对象 return 迭代器对象. The 抽象操作 CreateSetIterator with arguments set and kind is used to create such 迭代器对象. It 执行如下:
All Set 迭代器对象 继承属性 from the %SetIteratorPrototype% 内部对象. The %SetIteratorPrototype% 内部对象 is an 普通对象 and its [[Prototype]] 内部属性 is the %IteratorPrototype% 内部对象. In addition, %SetIteratorPrototype% 有以下属性:
Set 迭代器实例 are 普通对象 that 继承属性 from the %SetIteratorPrototype% 内部对象. Set 迭代器实例 are initially created with the 内部属性 specified in Table 58.
Table 58: 内部属性 of Set 迭代器实例
内部属性
Description
[[IteratedSet]]
The Set object that is being iterated.
[[SetNextIndex]]
The 整数索引 of the next Set data element to be examined by this 迭代器
[[SetIterationKind]]
A String 值 that identifies what is to be returned for each element of the iteration. The possible values are: "key", "value", "key+value". "key" and "value" have the same meaning.
23.3WeakMap 对象
WeakMap 对象 are collections of key/value pairs where the keys are objects and values may be arbitrary ES 语言值. A WeakMap may be queried to see if it contains a key/value pair with a specific key, but no mechanism is provided for enumerating the objects it holds as keys. If an object that is being used as the key of a WeakMap key/value pair is only reachable by following a chain of references that start within that WeakMap, then that key/value pair is inaccessible and is automatically removed from the WeakMap. WeakMap implementations must detect and remove such key/value pairs and any associated resources.
An 实现 may impose an arbitrarily determined latency between the time a key/value pair of a WeakMap becomes inaccessible and the time when the key/value pair is removed from the WeakMap. If this latency was observable to ES 程序, it would be a source of indeterminacy that could impact program execution. For that reason, an ES 实现 must not provide any means to observe a key of a WeakMap that does not require the observer to present the observed key.
WeakMap 对象 must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of key/value pairs in the collection. The data structure used in this WeakMap 对象 specification are only intended to describe the required observable 语义 of WeakMap 对象. It is not intended to be a viable 实现 model.
Note
WeakMap and WeakSets are intended to provide mechanisms for dynamically associating state with an object in a manner that does not “leak” memory resources if, in the absence of the WeakMap or WeakSet, the object otherwise became inaccessible and subject to resource reclamation by the 实现's garbage collection mechanisms. This characteristic can be achieved by using an inverted per-object mapping of weak map instances to keys. Alternatively each weak map may internally store its key to value mappings but this approach requires coordination between the WeakMap or WeakSet 实现 and the garbage collector. The following references describe mechanism that may be useful to implementations of WeakMap and WeakSets:
Barry Hayes. 1997. Ephemerons: a new finalization mechanism. In Proceedings of the 12th ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications (OOPSLA '97), A. Michael Berman (Ed.). ACM, New York, NY, USA, 176-183, http://doi.acm.org/10.1145/263698.263733.
The WeakMap 构造器 is the %WeakMap% 内部对象 and the 初始值 of the WeakMap property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 WeakMap object. WeakMap is not intended to be called as a function and will 抛出一个异常 when called in that manner.
The WeakMap构造器 被设计成可被子类化的. 它可以用作 the value in an extends clause of a class definition. 子类构造器 that 旨在继承特定的 WeakMap behaviour must include a super call to the WeakMap构造器 以便创建和初始化子类实例 with the 内部状态 necessary to support the WeakMap.prototype 内置方法.
23.3.1.1WeakMap ( [ iterable ] )
When the WeakMap function is called with 可选参数 iterable, 执行如下:
If the parameter iterable is present, it is expected to be an object that implements an @@迭代器 method that returns an 迭代器 object that produces a two element array-like object whose first element is a value that will be used as a WeakMap key and whose second element is the value to associate with that key.
The WeakMap 原型对象 is the 内部对象 %WeakMapPrototype%. [[Prototype]] 内部属性的值 of the WeakMap 原型对象 is the 内部对象 %ObjectPrototype%. The WeakMap 原型对象 is an 普通对象. It does not have a [[WeakMapData]] 内部属性.
23.3.3.1WeakMap.prototype.constructor
The 初始值 of WeakMap.prototype.constructor is the 内部对象 %WeakMap%.
For each Record {[[Key]], [[Value]]} p that is an element of entries, do
If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, then
Set p.[[Key]] to empty.
Set p.[[Value]] to empty.
Return true.
Return false.
Note
The value empty is used as a specification device to indicate that an entry has been deleted. Actual implementations may take other actions 例如 physically removing the entry from internal 数据结构.
WeakMap 实例 are 普通对象 that 继承属性 from the WeakMap prototype. WeakMap 实例 also have a [[WeakMapData]] 内部属性.
23.4WeakSet 对象
WeakSet 对象 are collections of objects. A distinct object may only occur once as an element of a WeakSet's collection. A WeakSet may be queried to see if it contains a specific object, but no mechanism is provided for enumerating the objects it holds. If an object that is contained by a WeakSet is only reachable by following a chain of references that start within that WeakSet, then that object is inaccessible and is automatically removed from the WeakSet. WeakSet implementations must detect and remove such objects and any associated resources.
An 实现 may impose an arbitrarily determined latency between the time an object contained in a WeakSet becomes inaccessible and the time when the object is removed from the WeakSet. If this latency was observable to ES 程序, it would be a source of indeterminacy that could impact program execution. For that reason, an ES 实现 must not provide any means to determine if a WeakSet contains a particular object that does not require the observer to present the observed object.
WeakSet 对象 must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structure used in this WeakSet 对象 specification is only intended to describe the required observable 语义 of WeakSet 对象. It is not intended to be a viable 实现 model.
The WeakSet 构造器 is the %WeakSet% 内部对象 and the 初始值 of the WeakSet property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 WeakSet object. WeakSet is not intended to be called as a function and will 抛出一个异常 when called in that manner.
The WeakSet构造器 被设计成可被子类化的. 它可以用作 the value in an extends clause of a class definition. 子类构造器 that 旨在继承特定的 WeakSet behaviour must include a super call to the WeakSet构造器 以便创建和初始化子类实例 with the 内部状态 necessary to support the WeakSet.prototype 内置方法.
23.4.1.1WeakSet ( [ iterable ] )
When the WeakSet function is called with 可选参数 iterable, 执行如下:
The WeakSet 原型对象 is the 内部对象 %WeakSetPrototype%. [[Prototype]] 内部属性的值 of the WeakSet 原型对象 is the 内部对象 %ObjectPrototype%. The WeakSet 原型对象 is an 普通对象. It does not have a [[WeakSetData]] 内部属性.
Let entries be the List that is S.[[WeakSetData]].
For each e that is an element of entries, do
If e is not empty and SameValue(e, value) is true, then
Replace the element of entries whose value is e with an element whose value is empty.
Return true.
Return false.
Note
The value empty is used as a specification device to indicate that an entry has been deleted. Actual implementations may take other actions 例如 physically removing the entry from internal 数据结构.
Detaching an ArrayBuffer instance disassociates the 数据块 used as its backing store from the instance and sets the byte length of the buffer to 0. No operations defined by this specification use the DetachArrayBuffer 抽象操作. However, an ES 实现 or host environment may define such operations.
The 抽象操作 CloneArrayBuffer takes four parameters, an ArrayBuffer srcBuffer, an integer offset srcByteOffset, an integer length srcLength, and a 构造器 function cloneConstructor. It creates a new ArrayBuffer whose data is a copy of srcBuffer's data over the range starting at srcByteOffset and continuing for srcLength bytes. This operation 执行如下:
Assert: Type(srcBuffer) is Object and it has an [[ArrayBufferData]] 内部属性.
The 抽象操作 RawBytesToNumber takes three parameters, a String type, a ListrawBytes, and a Boolean isLittleEndian. This operation 执行如下:
Let elementSize be the Number 值 of the Element Size value specified in Table 56 for Element Type type.
If isLittleEndian is false, reverse the order of the elements of rawBytes.
If type is "Float32", then
Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2008 binary32 value.
If value is an IEEE 754-2008 binary32 NaN value, return the NaN Number 值.
Return the Number 值 that corresponds to value.
If type is "Float64", then
Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2008 binary64 value.
If value is an IEEE 754-2008 binary64 NaN value, return the NaN Number 值.
Return the Number 值 that corresponds to value.
If the first 代码单元 of type is the 代码单元 0x0055 (LATIN CAPITAL LETTER U), then
Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of an unsigned little-endian binary number.
Else,
Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of a binary little-endian 2's complement number of bit length elementSize × 8.
The 抽象操作 GetValueFromBuffer takes six parameters, an ArrayBuffer or SharedArrayBuffer arrayBuffer, an integer byteIndex, a String type, a Boolean isTypedArray, a String order, and optionally a Boolean isLittleEndian. This operation 执行如下:
Let eventList be the [[EventList]] field of the element in execution.[[EventLists]] whose [[AgentSignifier]] is AgentSignifier().
If isTypedArray is true and type is "Int8", "Uint8", "Int16", "Uint16", "Int32", or "Uint32", let noTear be true; otherwise let noTear be false.
Let rawValue be a List of length elementSize of nondeterministically chosen byte values.
NOTE: In implementations, rawValue is the result of a non-atomic or atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the 内存模型 to describe observable behaviour of hardware with weak consistency.
Let readEvent be ReadSharedMemory{ [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }.
Append readEvent to eventList.
Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } to execution.[[ChosenValues]].
Else, let rawValue be a List of elementSize containing, in order, the elementSize sequence of bytes starting with block[byteIndex].
If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
The 抽象操作 NumberToRawBytes takes three parameters, a String type, a Number value, and a Boolean isLittleEndian. This operation 执行如下:
If type is "Float32", then
Let rawBytes be a List containing the 4 bytes that are the result of converting value to IEEE 754-2008 binary32 format using “Round to nearest, ties to even” rounding mode. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawBytes may be set to any 实现 chosen IEEE 754-2008 binary32 format Not-a-Number encoding. An 实现 must always choose the same encoding for each 实现 distinguishable NaN value.
Else if type is "Float64", then
Let rawBytes be a List containing the 8 bytes that are the IEEE 754-2008 binary64 format encoding of value. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawBytes may be set to any 实现 chosen IEEE 754-2008 binary64 format Not-a-Number encoding. An 实现 must always choose the same encoding for each 实现 distinguishable NaN value.
Else,
Let n be the Number 值 of the Element Size specified in Table 56 for Element Type type.
Let convOp be the 抽象操作 named in the Conversion Operation column in Table 56 for Element Type type.
Let intValue be convOp(value).
If intValue ≥ 0, then
Let rawBytes be a List containing the n-byte binary encoding of intValue. If isLittleEndian is false, the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order.
Else,
Let rawBytes be a List containing the n-byte binary 2's complement encoding of intValue. If isLittleEndian is false, the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order.
The 抽象操作 SetValueInBuffer takes seven parameters, an ArrayBuffer or SharedArrayBuffer arrayBuffer, an integer byteIndex, a String type, a Number value, a Boolean isTypedArray, a String order, and optionally a Boolean isLittleEndian. This operation 执行如下:
The 抽象操作 GetModifySetValueInBuffer takes six parameters, a SharedArrayBuffer arrayBuffer, 一个非负整数 byteIndex, a String type, a Number value, a semantic function op, and optionally a Boolean isLittleEndian. This operation 执行如下:
Let eventList be the [[EventList]] field of the element in execution.[[EventLists]] whose [[AgentSignifier]] is AgentSignifier().
Let rawBytesRead be a List of length elementSize of nondeterministically chosen byte values.
NOTE: In implementations, rawBytesRead is the result of a load-link, of a load-exclusive, or of an operand of a read-modify-write instruction on the underlying hardware. The nondeterminism is a semantic prescription of the 内存模型 to describe observable behaviour of hardware with weak consistency.
Let rmwEvent be ReadModifyWriteSharedMemory{ [[Order]]: "SeqCst", [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes, [[ModifyOp]]: op }.
Append rmwEvent to eventList.
Append Chosen Value Record { [[Event]]: rmwEvent, [[ChosenValue]]: rawBytesRead } to execution.[[ChosenValues]].
The ArrayBuffer 构造器 is the %ArrayBuffer% 内部对象 and the 初始值 of the ArrayBuffer property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 ArrayBuffer object. ArrayBuffer is not intended to be called as a function and will 抛出一个异常 when called in that manner.
The ArrayBuffer构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 ArrayBuffer behaviour must include a super call to the ArrayBuffer构造器 to create and initialize subclass instances with the 内部状态 necessary to support the ArrayBuffer.prototype 内置方法.
24.1.2.1ArrayBuffer ( length )
When the ArrayBuffer function is called with argument length, 执行如下:
ArrayBuffer[@@species] is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Return the this value.
The value of the name property of this function is "get [Symbol.species]".
Note
ArrayBuffer prototype methods normally use their this object's 构造器 to create a derived object. However, a subclass 构造器 may over-ride that default behaviour by redefining its @@species property.
24.1.4Properties of the ArrayBuffer 原型对象
The ArrayBuffer 原型对象 is the 内部对象 %ArrayBufferPrototype%. [[Prototype]] 内部属性的值 of the ArrayBuffer 原型对象 is the 内部对象 %ObjectPrototype%. The ArrayBuffer 原型对象 is an 普通对象. It does not have an [[ArrayBufferData]] or [[ArrayBufferByteLength]] 内部属性.
24.1.4.1get ArrayBuffer.prototype.byteLength
ArrayBuffer.prototype.byteLength is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
ArrayBuffer instances 继承属性 from the ArrayBuffer 原型对象. ArrayBuffer instances each have an [[ArrayBufferData]] 内部属性 and an [[ArrayBufferByteLength]] 内部属性.
ArrayBuffer instances whose [[ArrayBufferData]] is null are considered to be detached and all operators to access or modify data contained in the ArrayBuffer instance will fail.
The SharedArrayBuffer 构造器 is the %SharedArrayBuffer% 内部对象 and the 初始值 of the SharedArrayBuffer property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 SharedArrayBuffer object. SharedArrayBuffer is not intended to be called as a function and will 抛出一个异常 when called in that manner.
The SharedArrayBuffer构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 SharedArrayBuffer behaviour must include a super call to the SharedArrayBuffer构造器 to create and initialize subclass instances with the 内部状态 necessary to support the SharedArrayBuffer.prototype 内置方法.
Note
Unlike an ArrayBuffer, a SharedArrayBuffer cannot become detached, and its internal [[ArrayBufferData]] slot is never null.
24.2.2.1SharedArrayBuffer( length )
When the SharedArrayBuffer function is called with 可选参数 length, 执行如下:
SharedArrayBuffer[@@species] is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Return the this value.
The value of the name property of this function is "get [Symbol.species]".
24.2.4Properties of the SharedArrayBuffer 原型对象
The SharedArrayBuffer 原型对象 is the 内部对象 %SharedArrayBufferPrototype%. [[Prototype]] 内部属性的值 of the SharedArrayBuffer 原型对象 is the 内部对象 %ObjectPrototype%. The SharedArrayBuffer 原型对象 is an 普通对象. It does not have an [[ArrayBufferData]] or [[ArrayBufferByteLength]] 内部属性.
24.2.5Properties of the SharedArrayBuffer Instances
SharedArrayBuffer instances 继承属性 from the SharedArrayBuffer 原型对象. SharedArrayBuffer instances each have an [[ArrayBufferData]] 内部属性 and an [[ArrayBufferByteLength]] 内部属性.
Note
SharedArrayBuffer instances, unlike ArrayBuffer instances, are never detached.
24.3DataView 对象
24.3.1抽象操作 For DataView 对象
24.3.1.1GetViewValue ( view, requestIndex, isLittleEndian, type )
The 抽象操作 GetViewValue with arguments view, requestIndex, isLittleEndian, and type is used by functions on DataView instances to retrieve values from the view's buffer. It 执行如下:
24.3.1.2SetViewValue ( view, requestIndex, isLittleEndian, type, value )
The 抽象操作 SetViewValue with arguments view, requestIndex, isLittleEndian, type, and value is used by functions on DataView instances to store values into the view's buffer. It 执行如下:
The DataView 构造器 is the %DataView% 内部对象 and the 初始值 of the DataView property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 DataView object. DataView is not intended to be called as a function and will 抛出一个异常 when called in that manner.
The DataView构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 DataView behaviour must include a super call to the DataView构造器 to create and initialize subclass instances with the 内部状态 necessary to support the DataView.prototype 内置方法.
The DataView 原型对象 is the 内部对象 %DataViewPrototype%. [[Prototype]] 内部属性的值 of the DataView 原型对象 is the 内部对象 %ObjectPrototype%. The DataView 原型对象 is an 普通对象. It does not have a [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], or [[ByteOffset]] 内部属性.
24.3.4.1get DataView.prototype.buffer
DataView.prototype.buffer is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
DataView instances are 普通对象 that 继承属性 from the DataView 原型对象. DataView instances each have [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], and [[ByteOffset]] 内部属性.
Note
The value of the [[DataView]] 内部属性 is not used within this specification. The simple presence of that 内部属性 is used within the specification to identify objects created using the DataView构造器.
24.4Atomics 对象
Atomics 对象 is the %Atomics% 内部对象 and the 初始值 of the Atomics property of the 全局对象. Atomics 对象 is a single 普通对象.
Atomics 对象 provides functions that operate indivisibly (atomically) on shared memory array cells as well as functions that let 代理 wait for and dispatch primitive events. When used with discipline, the Atomics functions allow multi-agent programs that communicate through shared memory to execute in a well-understood order even on parallel CPUs. The rules that govern shared-memory communication are provided by the 内存模型, defined below.
A WaiterList is a semantic object that contains an ordered list of those 代理 that are waiting on a location (block, i) in shared memory; block is a 共享数据块 and i a byte offset into the memory of block.
The agent cluster has a store of WaiterList objects; the store is indexed by (block, i). WaiterLists are agent-independent: a lookup in the store of WaiterLists by (block, i) will result in the same WaiterList object in any agent in the agent cluster.
Operations on a WaiterList -- adding and removing waiting 代理, traversing the list of 代理, suspending and waking 代理 on the list -- may only be performed by 代理 that have entered the WaiterList's critical section.
The 抽象操作 GetWaiterList takes two arguments, a 共享数据块block and 一个非负整数 i. It 执行如下:
Perform LeaveCriticalSection(WL) and suspend W for up to timeout milliseconds, performing the combined operation in such a way that a wakeup that arrives after the critical section is exited but before the suspension takes effect is not lost. W can wake up either because the timeout expired or because it was woken explicitly by another agent calling WakeWaiter(WL, W), and not for any other reasons at all.
The embedding may delay waking W, e.g. for resource management reasons, but W must eventually be woken in order to guarantee forward progress.
24.4.1.11AtomicReadModifyWrite( typedArray, index, value, op )
The 抽象操作 AtomicReadModifyWrite takes four arguments, typedArray, index, value, and a pure combining operation op. The pure combining operation op takes two List of byte values arguments and returns a List of byte values. The operation atomically loads a value, combines it with another value, and stores the result of the combination. It returns the loaded value. It 执行如下:
Let add denote a semantic function of two List of byte values arguments that applies the addition operation to the Number values corresponding to the List of byte values arguments and returns a List of byte values corresponding to the result of that operation.
Let and denote a semantic function of two List of byte values arguments that applies the bitwise-and operation element-wise to the two arguments and returns a List of byte values corresponding to the result of that operation.
Let expectedBytes be NumberToRawBytes(elementType, expected, isLittleEndian).
Let elementSize be the Number 值 of the Element Size value specified in Table 56 for arrayTypeName.
Let offset be typedArray.[[ByteOffset]].
Let indexedPosition be (i × elementSize) + offset.
Let compareExchange denote a semantic function of two List of byte values arguments that returns the second argument if the first argument is element-wise equal to expectedBytes.
Atomics.isLockFree() is an optimization primitive. The intuition is that if the atomic step of an atomic primitive (compareExchange, load, store, add, sub, and, or, xor, or exchange) on a datum of size n bytes will be performed without the calling agent acquiring a lock outside the n bytes comprising the datum, then Atomics.isLockFree(n) will return true. High-performance 算法 will use Atomics.isLockFree to determine whether to use locks or atomic operations in critical sections. If an atomic primitive is not lock-free then it is often more efficient for an 算法 to provide its own locking.
Atomics.isLockFree(4) always returns true as that can be supported on all known relevant hardware. Being able to assume this will generally simplify programs.
Let or denote a semantic function of two List of byte values arguments that applies the bitwise-or operation element-wise to the two arguments and returns a List of byte values corresponding to the result of that operation.
Let subtract denote a semantic function of two List of byte values arguments that applies the subtraction operation to the Number values corresponding to the List of byte values arguments and returns a List of byte values corresponding to the result of that operation.
Let xor denote a semantic function of two List of byte values arguments that applies the bitwise-xor operation element-wise to the two arguments and returns a List of byte values corresponding to the result of that operation.
JSON 对象 is the %JSON% 内部对象 and the 初始值 of the JSON property of the 全局对象. JSON 对象 is a single 普通对象 that contains two functions, parse and stringify, that are used to parse and construct JSON texts. The JSON Data Interchange Format is defined in ECMA-404. The JSON interchange format used 在本规范中 is exactly that described by ECMA-404.
Conforming implementations of JSON.parse and JSON.stringify must support the exact interchange format described in the ECMA-404 规范 without any deletions or extensions to the format.
[[Prototype]] 内部属性的值 of JSON 对象 is the 内部对象 %ObjectPrototype%. The value of the [[Extensible]] 内部属性 of JSON 对象 is set to true.
JSON 对象 does not have a [[Construct]] 内部方法; it is not possible to use JSON 对象 as a 构造器 with new 运算符.
JSON 对象 does not have a [[Call]] 内部方法; it is not possible to invoke JSON 对象 as a function.
24.5.1JSON.parse ( text [ , reviver ] )
The parse function parses a JSON text (a JSON-formatted String) and produces an ES 值. The JSON format represents 字面量, arrays, and objects with a syntax similar to the syntax for ES 字面量, Array 初始化器, and Object 初始化器. After parsing, JSON 对象 are realized as ES 对象. JSON 数组 are realized as ES Array 实例. JSON strings, numbers, booleans, and null are realized as ES Strings, Numbers, Booleans, and null.
The optional reviver parameter is a function that takes two parameters, key and value. It can filter and transform the results. It is called with each of the key/value pairs produced by the parse, and its 返回值 is used instead of the original value. If it returns what it received, the structure is not modified. If it returns undefined then the property is deleted from the result.
Parse JText interpreted as UTF-16 encoded Unicode points (6.1.4) as a JSON text as specified in ECMA-404. 抛出一个 SyntaxError 异常 if JText is not a valid JSON text as defined in that specification.
Let completion be the result of parsing and evaluating scriptText as if it was the 源文本 of an ES Script, but using the alternative definition of DoubleStringCharacter provided below. The extended 属性定义估值 语义 defined in B.3.1 must not be used during the 估值.
Let unfiltered be completion.[[Value]].
Assert: unfiltered is either a String, Number, Boolean, Null, or an Object that is defined by either an ArrayLiteral or an ObjectLiteral.
JSON allows Unicode 代码单元 0x2028 (LINE SEPARATOR) and 0x2029 (PARAGRAPH SEPARATOR) to directly appear in 字符型字面量 without using an escape sequence. This is enabled by using the following alternative definition of DoubleStringCharacter when parsing scriptText in step 4:
Valid JSON text is a subset of the ES PrimaryExpression syntax as modified by Step 4 above. Step 2 verifies that JText conforms to that subset, and step 6 verifies that that parsing and 估值 returns a value of an appropriate type.
24.5.1.1运行时语义: InternalizeJSONProperty( holder, name )
The 抽象操作 InternalizeJSONProperty is a recursive 抽象操作 that takes two parameters: a holder object and the String name of a property in that object. InternalizeJSONProperty uses the value of reviver that was originally passed to the above parse function.
It is not permitted for a conforming 实现 of JSON.parse to extend the JSON grammars. If an 实现 wishes to support a modified or extended JSON interchange format it must do so by defining a different parse function.
Note
In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten.
24.5.2JSON.stringify ( value [ , replacer [ , space ] ] )
The stringify function returns a String in UTF-16 encoded JSON format representing an ES 值. It can take three parameters. The value parameter is an ES 值, which is usually an object or array, although it can also be a String, Boolean, Number or null. The optional replacer parameter is either a function that alters the way objects and arrays are stringified, or an array of Strings and Numbers that acts as an inclusion list for selecting the object properties that will be stringified. The optional space parameter is a String or Number that allows the result to have 空白 injected into it to improve human readability.
The length property of the stringify function is 3.
Note 1
JSON structures are allowed to be nested to any depth, but they must be acyclic. If value is or contains a cyclic structure, then the stringify function must 抛出一个 TypeError 异常. This is an example of a value that cannot be stringified:
a = [];
a[0] = a;
my_text = JSON.stringify(a); // This must 抛出一个 TypeError.
Note 2
Symbolic primitive values are rendered as follows:
The null value is rendered in JSON text as the String null.
The undefined value is not rendered.
The true value is rendered in JSON text as the String true.
The false value is rendered in JSON text as the String false.
Note 3
String values are wrapped in QUOTATION MARK (") 代码单元. The 代码单元 " and \ are escaped with \ prefixes. Control characters 代码单元 are replaced with escape sequences \uHHHH, or with the shorter forms, \b (BACKSPACE), \f (FORM FEED), \n (LINE FEED), \r (CARRIAGE RETURN), \t (CHARACTER TABULATION).
Note 4
Finite numbers are stringified as if by calling ToString(number). NaN and Infinity regardless of sign are represented as the String null.
Note 5
Values that do not have a JSON representation (例如 undefined and functions) do not produce a String. Instead they produce the undefined value. In arrays these values are represented as the String null. In objects an unrepresentable value causes the property to be excluded from stringification.
Note 6
An object is rendered as U+007B (LEFT CURLY BRACKET) followed by zero or more properties, separated with a U+002C (COMMA), closed with a U+007D (RIGHT CURLY BRACKET). A property is a quoted String representing the key or 属性名, a U+003A (COLON), and then the stringified property value. An array is rendered as an opening U+005B (LEFT SQUARE BRACKET followed by zero or more values, separated with a U+002C (COMMA), closed with a U+005D (RIGHT SQUARE BRACKET).
The 抽象操作 SerializeJSONProperty with arguments key, and holder has access to ReplacerFunction from the invocation of the stringify method. Its 算法 is as follows:
Else if C is the 代码单元 0x0008 (BACKSPACE), the 代码单元 0x000C (FORM FEED), the 代码单元 0x000A (LINE FEED), the 代码单元 0x000D (CARRIAGE RETURN), or the 代码单元 0x0009 (CHARACTER TABULATION), then
Set product to the string-concatenation of product and the 代码单元 0x005C (REVERSE SOLIDUS).
Let abbrev be the String 值 corresponding to the value of C as follows:
Set product to the string-concatenation of product and the 代码单元 0x0022 (QUOTATION MARK).
Return product.
24.5.2.3运行时语义: SerializeJSONObject ( value )
The 抽象操作 SerializeJSONObject with argument value serializes an object. It has access to the stack, indent, gap, and PropertyList values of the current invocation of the stringify method.
If stack contains value, 抛出一个 TypeError 异常 because the structure is cyclical.
Let properties be the String 值 formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with the 代码单元 0x002C (COMMA). A comma is not inserted either before the first String or after the last String.
Let separator be the string-concatenation of the 代码单元 0x002C (COMMA), the 代码单元 0x000A (LINE FEED), and indent.
Let properties be the String 值 formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with separator. The separator String is not inserted either before the first String or after the last String.
Let final be the string-concatenation of "{", the 代码单元 0x000A (LINE FEED), indent, properties, the 代码单元 0x000A (LINE FEED), stepback, and "}".
Remove the last element of stack.
Set indent to stepback.
Return final.
24.5.2.4运行时语义: SerializeJSONArray ( value )
The 抽象操作 SerializeJSONArray with argument value serializes an array. It has access to the stack, indent, and gap values of the current invocation of the stringify method.
If stack contains value, 抛出一个 TypeError 异常 because the structure is cyclical.
Let properties be the String 值 formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with the 代码单元 0x002C (COMMA). A comma is not inserted either before the first String or after the last String.
Let separator be the string-concatenation of the 代码单元 0x002C (COMMA), the 代码单元 0x000A (LINE FEED), and indent.
Let properties be the String 值 formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with separator. The separator String is not inserted either before the first String or after the last String.
Let final be the string-concatenation of "[", the 代码单元 0x000A (LINE FEED), indent, properties, the 代码单元 0x000A (LINE FEED), stepback, and "]".
Remove the last element of stack.
Set indent to stepback.
Return final.
Note
The representation of arrays includes only the elements between zero and array.length - 1 inclusive. Properties whose keys are not array indexes are excluded from the stringification. An array is stringified as an opening LEFT SQUARE BRACKET, elements separated by COMMA, and a closing RIGHT SQUARE BRACKET.
24.5.3JSON [ @@toStringTag ]
The 初始值 of the @@toStringTag property is the String 值 "JSON".
An interface is a set of 属性键 whose associated values match a specific specification. Any object that provides all the properties as described by an interface's specification conforms to that interface. An interface is not represented by a distinct object. There may be many separately implemented objects that conform to any interface. An individual object may conform to multiple interfaces.
25.1.1.1The Iterable Interface
The Iterable interface includes the property described in Table 59:
Table 59: Iterable Interface Required Properties
Property
Value
Requirements
@@迭代器
A function that returns an 迭代器 object.
The returned object must conform to the 迭代器 interface.
25.1.1.2The 迭代器 Interface
An object that implements the 迭代器 interface must include the property in Table 60. Such objects may also implement the properties in Table 61.
Table 60: 迭代器 Interface Required Properties
Property
Value
Requirements
next
A function that returns an IteratorResult object.
The returned object must conform to the IteratorResult interface. If a previous call to the next method of an 迭代器 has returned an IteratorResult object whose done property is true, then all subsequent calls to the next method of that object should also return an IteratorResult object whose done property is true. However, this requirement is not enforced.
Note 1
Arguments may be passed to the next function but their interpretation and validity is dependent upon the target 迭代器. The for-of statement and other common users of Iterators do not pass any arguments, so 迭代器 objects that expect to be used in such a manner must be prepared to deal with being called with no arguments.
Table 61: 迭代器 Interface Optional Properties
Property
Value
Requirements
return
A function that returns an IteratorResult object.
The returned object must conform to the IteratorResult interface. Invoking this method notifies the 迭代器 object that the caller does not intend to make any more next method calls to the 迭代器. The returned IteratorResult object will typically have a done property whose value is true, and a value property with the value passed as the argument of the return method. However, this requirement is not enforced.
throw
A function that returns an IteratorResult object.
The returned object must conform to the IteratorResult interface. Invoking this method notifies the 迭代器 object that the caller has detected an error condition. The argument may be used to identify the error condition and typically will be an 异常 object. A typical response is to throw the value passed as the argument. If the method does not throw, the returned IteratorResult object will typically have a done property whose value is true.
Note 2
Typically callers of these methods should check for their existence before invoking them. Certain ES language features including for-of, yield*, and array destructuring call these methods after performing an existence check. Most ES library functions that accept Iterable objects as arguments also conditionally call them.
25.1.1.3The AsyncIterable Interface
The AsyncIterable interface includes the properties described in Table 62:
The returned object must conform to the AsyncIterator interface.
25.1.1.4The AsyncIterator Interface
An object that implements the AsyncIterator interface must include the properties in Table 63. Such objects may also implement the properties in Table 64.
A function that returns a promise for an IteratorResult object.
The returned promise, when fulfilled, must fulfill with an object which conforms to the IteratorResult interface. If a previous call to the next method of an AsyncIterator has returned a promise for an IteratorResult object whose done property is true, then all subsequent calls to the next method of that object should also return a promise for an IteratorResult object whose done property is true. However, this requirement is not enforced.
Additionally, the IteratorResult object that serves as a fulfillment value should have a value property whose value is not a promise (or "thenable"). However, this requirement is also not enforced.
Note 1
Arguments may be passed to the next function but their interpretation and validity is dependent upon the target AsyncIterator. The for-await-of statement and other common users of AsyncIterators do not pass any arguments, so AsyncIterator objects that expect to be used in such a manner must be prepared to deal with being called with no arguments.
A function that returns a promise for an IteratorResult object.
The returned promise, when fulfilled, must fulfill with an object which conforms to the IteratorResult interface. Invoking this method notifies the AsyncIterator object that the caller does not intend to make any more next method calls to the AsyncIterator. The returned promise will fulfill with an IteratorResult object which will typically have a done property whose value is true, and a value property with the value passed as the argument of the return method. However, this requirement is not enforced.
Additionally, the IteratorResult object that serves as a fulfillment value should have a value property whose value is not a promise (or "thenable"). If the argument value is used in the typical manner, then if it is a rejected promise, a promise rejected with the same reason should be returned; if it is a fulfilled promise, then its fulfillment value should be used as the value property of the returned promise's IteratorResult object fulfillment value. However, these requirements are also not enforced.
throw
A function that returns a promise for an IteratorResult object.
The returned promise, when fulfilled, must fulfill with an object which conforms to the IteratorResult interface. Invoking this method notifies the AsyncIterator object that the caller has detected an error condition. The argument may be used to identify the error condition and typically will be an 异常 object. A typical response is to return a rejected promise which rejects with the value passed as the argument.
If the returned promise is fulfilled, the IteratorResult fulfillment value will typically have a done property whose value is true. Additionally, it should have a value property whose value is not a promise (or "thenable"), but this requirement is not enforced.
Note 2
Typically callers of these methods should check for their existence before invoking them. Certain ES language features including for-await-of and yield* call these methods after performing an existence check.
25.1.1.5The IteratorResult Interface
The IteratorResult interface includes the properties listed in Table 65:
Table 65: IteratorResult Interface Properties
Property
Value
Requirements
done
Either true or false.
This is the result status of an 迭代器next method call. If the end of the 迭代器 was reached done is true. If the end was not reached done is false and a value is available. If a done property (either own or inherited) does not exist, it is consider to have the value false.
If done is false, this is the current iteration element value. If done is true, this is the 返回值 of the 迭代器, if it supplied one. If the 迭代器 does not have a 返回值, value is undefined. In that case, the value property may be absent from the conforming object if it does not inherit an explicit value property.
25.1.2The %IteratorPrototype% Object
[[Prototype]] 内部属性的值 of the %IteratorPrototype% object is the 内部对象 %ObjectPrototype%. The %IteratorPrototype% object is an 普通对象. The 初始值 of the [[Extensible]] 内部属性 of the %IteratorPrototype% object is true.
Note
所有定义在本规范中的对象 that implement the 迭代器 interface also inherit from %IteratorPrototype%. ES 代码 may also define objects that inherit from %IteratorPrototype%.The %IteratorPrototype% object provides a place where additional methods that are applicable to all 迭代器对象 may be added.
The following expression is one way that ES 代码 can access the %IteratorPrototype% object:
The value of the name property of this function is "[Symbol.迭代器]".
25.1.3The %AsyncIteratorPrototype% Object
[[Prototype]] 内部属性的值 of the %AsyncIteratorPrototype% object is the 内部对象 %ObjectPrototype%. The %AsyncIteratorPrototype% object is an 普通对象. The 初始值 of the [[Extensible]] 内部属性 of the %AsyncIteratorPrototype% object is true.
Note
所有定义在本规范中的对象 that implement the AsyncIterator interface also inherit from %AsyncIteratorPrototype%. ES 代码 may also define objects that inherit from %AsyncIteratorPrototype%.The %AsyncIteratorPrototype% object provides a place where additional methods that are applicable to all async 迭代器对象 may be added.
The value of the name property of this function is "[Symbol.asyncIterator]".
25.1.4Async-from-Sync 迭代器对象
An Async-from-Sync 迭代器 object is an async 迭代器 that adapts a specific synchronous 迭代器. There is not a named 构造器 for Async-from-Sync 迭代器对象. Instead, Async-from-Sync 迭代器对象 are created by the CreateAsyncFromSyncIterator 抽象操作 as needed.
All Async-from-Sync 迭代器对象 继承属性 from the %AsyncFromSyncIteratorPrototype% 内部对象. The %AsyncFromSyncIteratorPrototype% object is an 普通对象 and its [[Prototype]] 内部属性 is the %AsyncIteratorPrototype% 内部对象. In addition, %AsyncFromSyncIteratorPrototype% 有以下属性:
25.1.4.2.1%AsyncFromSyncIteratorPrototype%.next ( value )
25.1.4.2.5Async-from-Sync 迭代器 Value Unwrap Functions
An async-from-sync 迭代器 value unwrap function is an anonymous 内置函数 that is used by methods of %AsyncFromSyncIteratorPrototype% when processing the value field of an IteratorResult object, in order to wait for its value if it is a promise and re-package the result in a new "unwrapped" IteratorResult object. Each async 迭代器 value unwrap function has a [[Done]] 内部属性.
When an async-from-sync 迭代器 value unwrap function F is called with argument value, 执行如下:
Async-from-Sync 迭代器实例 are 普通对象 that 继承属性 from the %AsyncFromSyncIteratorPrototype% 内部对象. Async-from-Sync 迭代器实例 are initially created with the 内部属性 listed in Table 66.
Table 66: 内部属性 of Async-from-Sync 迭代器实例
内部属性
Description
[[SyncIteratorRecord]]
A Record, of the type returned by GetIterator, representing the original synchronous 迭代器 which is being adapted.
The GeneratorFunction构造器 is the %GeneratorFunction% intrinsic. When GeneratorFunction 被作为一个函数调用而不是一个 构造器, 它会创建和初始化一个新的 GeneratorFunction object. Thus the function call GeneratorFunction (…) is equivalent to the object creation expression new GeneratorFunction (…) with the same arguments.
GeneratorFunction 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 GeneratorFunction behaviour must include a super call to the GeneratorFunction构造器 to create and initialize subclass instances with the 内部属性 necessary for 内置 GeneratorFunction behaviour. All ES syntactic forms for defining generator 函数对象 create direct instances of GeneratorFunction. There is no syntactic means to create instances of GeneratorFunction subclasses.
25.2.1.1GeneratorFunction ( p1, p2, … , pn, body )
The last argument specifies the body (executable code) of a 生成器函数; any preceding arguments specify formal parameters.
When the GeneratorFunction function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no “p” arguments, and where body might also not be provided), 执行如下:
The GeneratorFunction 原型对象 is an 普通对象. It is not a 函数对象 and does not have an [[ECMAScriptCode]] 内部属性 or any other of the 内部属性 listed in Table 27 or Table 67. In addition to being the value of the prototype property of the %GeneratorFunction% intrinsic, it is the %Generator% intrinsic (see Figure 2).
[[Prototype]] 内部属性的值 of the GeneratorFunction 原型对象 is the %FunctionPrototype% 内部对象. The 初始值 of the [[Extensible]] 内部属性 of the GeneratorFunction 原型对象 is true.
25.2.3.1GeneratorFunction.prototype.constructor
The 初始值 of GeneratorFunction.prototype.constructor is the 内部对象 %GeneratorFunction%.
Every GeneratorFunction instance is an ES 函数对象 and has the 内部属性 listed in Table 27. The value of the [[FunctionKind]] 内部属性 for all such instances is "generator".
Each GeneratorFunction instance 拥有以下自身属性:
25.2.4.1length
The specification for the length property of 函数实例 given in 19.2.4.1 also applies to 生成器函数实例.
25.2.4.2name
The specification for the name property of 函数实例 given in 19.2.4.2 also applies to 生成器函数实例.
25.2.4.3prototype
Whenever a GeneratorFunction instance is created another 普通对象 is also created and is the 初始值 of the 生成器函数's prototype property. The value of the prototype property is used to initialize the [[Prototype]] 内部属性 of a newly created 生成器对象 when the generator 函数对象 is invoked using [[Call]].
Unlike 函数实例, the object that is the value of the a GeneratorFunction's prototype property does not have a 构造器 property whose value is the GeneratorFunction instance.
The AsyncGeneratorFunction构造器 is the %AsyncGeneratorFunction% intrinsic. When AsyncGeneratorFunction 被作为一个函数调用而不是一个 构造器, 它会创建和初始化一个新的 AsyncGeneratorFunction object. Thus the function call AsyncGeneratorFunction (...) is equivalent to the object creation expression new AsyncGeneratorFunction (...) with the same arguments.
AsyncGeneratorFunction 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 AsyncGeneratorFunction behaviour must include a super call to the AsyncGeneratorFunction构造器 to create and initialize subclass instances with the 内部属性 necessary for 内置 AsyncGeneratorFunction behaviour. All ES syntactic forms for defining async generator 函数对象 create direct instances of AsyncGeneratorFunction. There is no syntactic means to create instances of AsyncGeneratorFunction subclasses.
25.3.1.1AsyncGeneratorFunction ( p1, p2, ..., pn, body )
The last argument specifies the body (executable code) of an async 生成器函数; any preceding arguments specify formal parameters.
When the AsyncGeneratorFunction function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no "p" arguments, and where body might also not be provided), 执行如下:
The AsyncGeneratorFunction构造器 is a 标准内置 函数对象 that inherits from the Function构造器. [[Prototype]] 内部属性的值 of the AsyncGeneratorFunction构造器 is the 内部对象 %Function%.
The value of the [[Extensible]] 内部属性 of the AsyncGeneratorFunction 构造器 is true.
The value of the name property of the AsyncGeneratorFunction is "AsyncGeneratorFunction".
The AsyncGeneratorFunction 原型对象 is an 普通对象. It is not a 函数对象 and does not have an [[ECMAScriptCode]] 内部属性 or any other of the 内部属性 listed in Table 27 or Table 68. In addition to being the value of the prototype property of the %AsyncGeneratorFunction% intrinsic, it is the %AsyncGenerator% intrinsic.
[[Prototype]] 内部属性的值 of the AsyncGeneratorFunction 原型对象 is the %FunctionPrototype% 内部对象. The 初始值 of the [[Extensible]] 内部属性 of the AsyncGeneratorFunction 原型对象 is true.
Every AsyncGeneratorFunction instance is an ES 函数对象 and has the 内部属性 listed in Table 27. The value of the [[FunctionKind]] 内部属性 for all such instances is "generator".
Each AsyncGeneratorFunction instance 拥有以下自身属性:
25.3.4.1length
The value of the length property is an integer that indicates the typical number of arguments expected by the AsyncGeneratorFunction. However, the language permits the function to be invoked with some other number of arguments. The behaviour of an AsyncGeneratorFunction when invoked on a number of arguments other than the number specified by its length property depends on the function.
The specification for the name property of 函数实例 given in 19.2.4.2 also applies to 异步生成器函数实例.
25.3.4.3prototype
Whenever an AsyncGeneratorFunction instance is created another 普通对象 is also created and is the 初始值 of the async 生成器函数's prototype property. The value of the prototype property is used to initialize the [[Prototype]] 内部属性 of a newly created AsyncGenerator object when the generator 函数对象 is invoked using [[Call]].
Unlike 函数实例, the object that is the value of the an AsyncGeneratorFunction's prototype property does not have a 构造器 property whose value is the AsyncGeneratorFunction instance.
25.4生成器对象
A 生成器对象 is an instance of a 生成器函数 and conforms to both the 迭代器 and Iterable interfaces.
生成器实例 directly 继承属性 from the object that is the value of the prototype property of the 生成器函数 that created the instance. 生成器实例 indirectly 继承属性 from the Generator Prototype intrinsic, %GeneratorPrototype%.
25.4.1生成器原型的属性
The Generator 原型对象 is the %GeneratorPrototype% intrinsic. It is also the 初始值 of the prototype property of the %Generator% intrinsic (the GeneratorFunction.prototype).
The Generator prototype is an 普通对象. It is not a Generator instance and does not have a [[GeneratorState]] 内部属性.
[[Prototype]] 内部属性的值 of the Generator 原型对象 is the 内部对象 %IteratorPrototype%. The 初始值 of the [[Extensible]] 内部属性 of the Generator 原型对象 is true.
All 生成器实例 indirectly 继承属性 of the Generator 原型对象.
25.4.1.1Generator.prototype.constructor
The 初始值 of Generator.prototype.constructor is the 内部对象 %Generator%.
Once a generator enters the "completed" state it never leaves it and its associated 执行上下文 is never resumed. Any execution state associated with generator can be discarded at this point.
If result.[[Type]] is normal, let resultValue be undefined.
Else if result.[[Type]] is return, let resultValue be result.[[Value]].
Push genContext onto the 执行上下文 堆栈; genContext is now the 运行时执行上下文.
Resume the suspended 估值 of genContext using NormalCompletion(value) as the result of the operation that suspended it. Let result be the value returned by the resumed computation.
Assert: When we return here, genContext has already been removed from the 执行上下文 堆栈 and methodContext is the currently 运行时执行上下文.
Once a generator enters the "completed" state it never leaves it and its associated 执行上下文 is never resumed. Any execution state associated with generator can be discarded at this point.
Push genContext onto the 执行上下文 堆栈; genContext is now the 运行时执行上下文.
Resume the suspended 估值 of genContext using abruptCompletion as the result of the operation that suspended it. Let result be the 完成记录 returned by the resumed computation.
Assert: When we return here, genContext has already been removed from the 执行上下文 堆栈 and methodContext is the currently 运行时执行上下文.
NOTE: This returns to the 估值 of the operation that had most previously resumed 估值 of genContext.
25.5异步生成器对象
An AsyncGenerator object is an instance of an async 生成器函数 and conforms to both the AsyncIterator and AsyncIterable interfaces.
AsyncGenerator instances directly 继承属性 from the object that is the value of the prototype property of the AsyncGenerator function that created the instance. AsyncGenerator instances indirectly 继承属性 from the AsyncGenerator Prototype intrinsic, %AsyncGeneratorPrototype%.
25.5.1异步生成器原型的属性
The AsyncGenerator 原型对象 is the %AsyncGeneratorPrototype% intrinsic. It is also the 初始值 of the prototype property of the %AsyncGenerator% intrinsic (the AsyncGeneratorFunction.prototype).
The AsyncGenerator prototype is an 普通对象. It is not an AsyncGenerator instance and does not have an [[AsyncGeneratorState]] 内部属性.
[[Prototype]] 内部属性的值 of the AsyncGenerator 原型对象 is the 内部对象 %AsyncIteratorPrototype%. The 初始值 of the [[Extensible]] 内部属性 of the AsyncGenerator 原型对象 is true.
All AsyncGenerator instances indirectly 继承属性 of the AsyncGenerator 原型对象.
25.5.1.1AsyncGenerator.prototype.constructor
The 初始值 of AsyncGenerator.prototype.constructor is the 内部对象 %AsyncGenerator%.
AsyncGenerator instances are initially created with the 内部属性 described below:
Table 68: 内部属性 of AsyncGenerator Instances
内部属性
Description
[[AsyncGeneratorState]]
The current execution state of the async generator. The possible values are: undefined, "suspendedStart", "suspendedYield", "executing", "awaiting-return", and "completed".
[[AsyncGeneratorContext]]
The 执行上下文 that is used when executing the code of this async generator.
[[AsyncGeneratorQueue]]
A List of AsyncGeneratorRequest records which represent requests to resume the async generator.
25.5.3异步生成器抽象操作
25.5.3.1AsyncGeneratorRequest Records
The AsyncGeneratorRequest is a Record value used to store information about how an async generator should be resumed and contains capabilities for fulfilling or rejecting the corresponding promise.
Set generator.[[AsyncGeneratorState]] to "executing".
Push genContext onto the 执行上下文 堆栈; genContext is now the 运行时执行上下文.
Resume the suspended 估值 of genContext using completion as the result of the operation that suspended it. Let result be the 完成记录 returned by the resumed computation.
NOTE: This returns to the 估值 of the operation that had most previously resumed 估值 of genContext.
25.6Promise 对象
A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.
Any promise 对象 is in one of three mutually exclusive states: fulfilled, rejected, and pending:
A promise p is fulfilled if p.then(f, r) will immediately enqueue a Job to call the function f.
A promise p is rejected if p.then(f, r) will immediately enqueue a Job to call the function r.
A promise is pending if it is neither fulfilled nor rejected.
A promise is said to be settled if it is not pending, i.e. if it is either fulfilled or rejected.
A promise is resolved if it is settled or if it has been “locked in” to match the state of another promise. Attempting to resolve or reject a resolved promise has no effect. A promise is unresolved if it is not resolved. An unresolved promise is always in the pending state. A resolved promise may be pending, fulfilled or rejected.
25.6.1Promise 抽象操作
25.6.1.1PromiseCapability Records
A PromiseCapability is a Record value used to encapsulate a promise 对象 along with the functions that are capable of resolving or rejecting that promise 对象. PromiseCapability Records are produced by the NewPromiseCapability 抽象操作.
PromiseCapability Records have the fields listed in Table 70.
Else if value is a 完成记录, let value be value.[[Value]].
25.6.1.2PromiseReaction Records
The PromiseReaction is a Record value used to store information about how a promise should react when it becomes resolved or rejected with a given value. PromiseReaction records are created by the PerformPromiseThen 抽象操作, and are used by a PromiseReactionJob.
PromiseReaction records have the fields listed in Table 71.
The function that should be applied to the incoming value, and whose 返回值 will govern what happens to the derived promise. If [[Handler]] is undefined, a function that depends on the value of [[Type]] will be used instead.
25.6.1.3CreateResolvingFunctions ( promise )
When CreateResolvingFunctions is performed with argument promise, 执行如下:
Let alreadyResolved be a new Record { [[Value]]: false }.
Let stepsResolve be the 算法步骤 defined in Promise Resolve Functions (25.6.1.3.2).
Let resolve be CreateBuiltinFunction(stepsResolve, « [[Promise]], [[AlreadyResolved]] »).
Set resolve.[[Promise]] to promise.
Set resolve.[[AlreadyResolved]] to alreadyResolved.
Let stepsReject be the 算法步骤 defined in Promise Reject Functions (25.6.1.3.1).
Let reject be CreateBuiltinFunction(stepsReject, « [[Promise]], [[AlreadyResolved]] »).
Set reject.[[Promise]] to promise.
Set reject.[[AlreadyResolved]] to alreadyResolved.
Return a new Record { [[Resolve]]: resolve, [[Reject]]: reject }.
25.6.1.3.1Promise Reject Functions
A promise reject function is an anonymous 内置函数 that has [[Promise]] and [[AlreadyResolved]] 内部属性.
When a promise reject function F is called with argument reason, 执行如下:
Assert: F has a [[Promise]] 内部属性 whose value is an Object.
Let promise be F.[[Promise]].
Let alreadyResolved be F.[[AlreadyResolved]].
If alreadyResolved.[[Value]] is true, return undefined.
The 抽象操作 NewPromiseCapability takes a 构造器 function, and attempts to use that 构造器 function in the fashion of the 内置 Promise构造器 to create a promise 对象 and extract its resolve and reject functions. The promise plus the resolve and reject functions are used to initialize a new PromiseCapability Record which is returned as the value of this 抽象操作.
If IsCallable(promiseCapability.[[Resolve]]) is false, 抛出一个 TypeError 异常.
If IsCallable(promiseCapability.[[Reject]]) is false, 抛出一个 TypeError 异常.
Set promiseCapability.[[Promise]] to promise.
Return promiseCapability.
Note
This 抽象操作 supports Promise subclassing, as it is generic on any 构造器 that calls a passed executor function argument in the same way as the Promise 构造器. It is used to generalize static methods of the Promise 构造器 to any subclass.
25.6.1.5.1GetCapabilitiesExecutor Functions
A GetCapabilitiesExecutor function is an anonymous 内置函数 that has a [[Capability]] 内部属性.
When a GetCapabilitiesExecutor function F is called with arguments resolve and reject, 执行如下:
Assert: F has a [[Capability]] 内部属性 whose value is a PromiseCapability Record.
Let promiseCapability be F.[[Capability]].
If promiseCapability.[[Resolve]] is not undefined, 抛出一个 TypeError 异常.
If promiseCapability.[[Reject]] is not undefined, 抛出一个 TypeError 异常.
Set promiseCapability.[[Resolve]] to resolve.
Set promiseCapability.[[Reject]] to reject.
Return undefined.
The length property of a GetCapabilitiesExecutor function is 2.
25.6.1.6IsPromise ( x )
The 抽象操作 IsPromise checks for the promise brand on an object.
The 抽象操作 TriggerPromiseReactions takes a collection of PromiseReactionRecords and enqueues a new Job for each record. Each such Job processes the [[Type]] and [[Handler]] of the PromiseReactionRecord, and if the [[Handler]] is a function, calls it passing the given argument. If the [[Handler]] is undefined, the behaviour is determined by the [[Type]].
For each reaction in reactions, in original insertion order, do
HostPromiseRejectionTracker is an 实现-defined 抽象操作 that allows 宿主环境 to track promise rejections.
An 实现 of HostPromiseRejectionTracker must complete normally in all cases. The default 实现 of HostPromiseRejectionTracker is to unconditionally return an empty normal completion.
Note 1
HostPromiseRejectionTracker is called in two scenarios:
When a promise is rejected without any handlers, it is called with its operation argument set to "reject".
When a handler is added to a rejected promise for the first time, it is called with its operation argument set to "handle".
A typical 实现 of HostPromiseRejectionTracker might try to notify developers of unhandled rejections, while also being careful to notify them if such previous notifications are later invalidated by new handlers being attached.
Note 2
If operation is "handle", an 实现 should not hold a reference to promise in a way that would interfere with garbage collection. An 实现 may hold a reference to promise if operation is "reject", since it is expected that rejections will be rare and not on hot code paths.
25.6.2Promise 作业
25.6.2.1PromiseReactionJob ( reaction, argument )
The job PromiseReactionJob with parameters reaction and argument applies the appropriate handler to the incoming value, and uses the handler's 返回值 to resolve or reject the derived promise associated with that handler.
This Job uses the supplied thenable and its then method to resolve the given promise. This process must take place as a Job to ensure that the 估值 of the then method occurs after 估值 of any surrounding code has completed.
25.6.3Promise 构造器
The Promise 构造器 is the %Promise% 内部对象 and the 初始值 of the Promise property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 promise 对象. Promise is not intended to be called as a function and will 抛出一个异常 when called in that manner.
The Promise构造器 被设计成可被子类化的. 它可以用作 the value in an extends clause of a class definition. 子类构造器 that 旨在继承特定的 Promise behaviour must include a super call to the Promise构造器 以便创建和初始化子类实例 with the 内部状态 necessary to support the Promise and Promise.prototype 内置方法.
25.6.3.1Promise ( executor )
When the Promise function is called with argument executor, 执行如下:
If NewTarget is undefined, 抛出一个 TypeError 异常.
If IsCallable(executor) is false, 抛出一个 TypeError 异常.
Let promise be ? OrdinaryCreateFromConstructor(NewTarget, "%PromisePrototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »).
Set promise.[[PromiseState]] to "pending".
Set promise.[[PromiseFulfillReactions]] to a new empty List.
Set promise.[[PromiseRejectReactions]] to a new empty List.
The executor argument must be a 函数对象. It is called for initiating and reporting completion of the possibly deferred action represented by this promise 对象. The executor is called with two arguments: resolve and reject. These are functions that may be used by the executor function to report eventual completion or failure of the deferred computation. Returning from the executor function does not mean that the deferred action has been completed but only that the request to eventually perform the deferred action has been accepted.
The resolve function that is passed to an executor function accepts a single argument. The executor code may eventually call the resolve function to indicate that it wishes to resolve the associated promise 对象. The argument passed to the resolve function represents the eventual value of the deferred action and can be either the actual fulfillment value or another promise 对象 which will provide the value if it is fulfilled.
The reject function that is passed to an executor function accepts a single argument. The executor code may eventually call the reject function to indicate that the associated Promise is rejected and will never be fulfilled. The argument passed to the reject function is used as the rejection value of the promise. Typically it will be an Error object.
The resolve and reject functions passed to an executor function by the Promise 构造器 have the capability to actually resolve and reject the associated promise. Subclasses may have different 构造器 behaviour that passes in customized values for resolve and reject.
The all function returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejects with the reason of the first passed promise that rejects. It resolves all elements of the passed iterable to promises as it runs this 算法.
A Promise.all resolve element function is an anonymous 内置函数 that is used to resolve a specific Promise.all element. Each Promise.all resolve element function has [[Index]], [[Values]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] 内部属性.
When a Promise.all resolve element function F is called with argument x, 执行如下:
Let alreadyCalled be F.[[AlreadyCalled]].
If alreadyCalled.[[Value]] is true, return undefined.
Set alreadyCalled.[[Value]] to true.
Let index be F.[[Index]].
Let values be F.[[Values]].
Let promiseCapability be F.[[Capability]].
Let remainingElementsCount be F.[[RemainingElements]].
Set values[index] to x.
Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
The race function returns a new promise which is settled in the same way as the first passed promise to settle. It resolves all elements of the passed iterable to promises as it runs this 算法.
If the iterable argument is empty or if none of the promises in iterable ever settle then the pending promise returned by this method will never be settled.
Note 2
The race function expects its this value to be a 构造器 function that supports the parameter conventions of the Promise构造器. It also expects that its this value provides a resolve method.
Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).
Return promiseCapability.[[Promise]].
This function is the %Promise_reject% 内部对象.
Note
The reject function expects its this value to be a 构造器 function that supports the parameter conventions of the Promise构造器.
25.6.4.5Promise.resolve ( x )
The resolve function returns either a new promise resolved with the passed argument, or the argument itself if the argument is a promise produced by this 构造器.
Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »).
Return promiseCapability.[[Promise]].
25.6.4.6get Promise [ @@species ]
Promise[@@species] is an 访问器属性 whose set 访问器函数 is undefined. Its get 访问器函数 执行如下:
Return the this value.
The value of the name property of this function is "get [Symbol.species]".
Note
Promise prototype methods normally use their this object's 构造器 to create a derived object. However, a subclass 构造器 may over-ride that default behaviour by redefining its @@species property.
25.6.5Promise 原型对象的属性
The Promise 原型对象 is the 内部对象 %PromisePrototype%. [[Prototype]] 内部属性的值 of the Promise 原型对象 is the 内部对象 %ObjectPrototype%. The Promise 原型对象 is an 普通对象. It does not have a [[PromiseState]] 内部属性 or any of the other 内部属性 of Promise 实例.
25.6.5.1Promise.prototype.catch ( onRejected )
When the catch method is called with argument onRejected, 执行如下:
A Then Finally function is an anonymous 内置函数 that has a [[构造器]] and an [[OnFinally]] 内部属性. The value of the [[构造器]] 内部属性 is a Promise-like 构造器函数对象, and the value of the [[OnFinally]] 内部属性 is a 函数对象.
When a Then Finally function F is called with argument value, 执行如下:
The length property of a Then Finally function is 1.
25.6.5.3.2Catch Finally Functions
A Catch Finally function is an anonymous 内置函数 that has a [[构造器]] and an [[OnFinally]] 内部属性. The value of the [[构造器]] 内部属性 is a Promise-like 构造器函数对象, and the value of the [[OnFinally]] 内部属性 is a 函数对象.
When a Catch Finally function F is called with argument reason, 执行如下:
The 抽象操作 PerformPromiseThen performs the “then” operation on promise using onFulfilled and onRejected as its settlement actions. The result is resultCapability's promise.
Promise 实例 are 普通对象 that 继承属性 from the Promise 原型对象 (the intrinsic, %PromisePrototype%). Promise 实例 are initially created with the 内部属性 described in Table 72.
Table 72: 内部属性 of Promise 实例
内部属性
Description
[[PromiseState]]
A String 值 that governs how a promise will react to incoming calls to its then method. The possible values are: "pending", "fulfilled", and "rejected".
[[PromiseResult]]
The value with which the promise has been fulfilled or rejected, if any. Only meaningful if [[PromiseState]] is not "pending".
[[PromiseFulfillReactions]]
A List of PromiseReaction records to be processed when/if the promise transitions from the "pending" state to the "fulfilled" state.
[[PromiseRejectReactions]]
A List of PromiseReaction records to be processed when/if the promise transitions from the "pending" state to the "rejected" state.
[[PromiseIsHandled]]
A boolean indicating whether the promise has ever had a fulfillment or rejection handler; used in unhandled rejection tracking.
The AsyncFunction构造器 is the %AsyncFunction% 内部对象 and is a subclass of Function. When AsyncFunction 被作为一个函数调用而不是一个 构造器, 它会创建和初始化一个新的 AsyncFunction object. Thus the function call AsyncFunction(…) is equivalent to the object creation expression new AsyncFunction(…) with the same arguments.
The AsyncFunction构造器 被设计成可被子类化的. 它可以用作 the value of an extends clause of a class definition. 子类构造器 that 旨在继承特定的 AsyncFunction behaviour must include a super call to the AsyncFunction 构造器 to create and initialize a subclass instance with the 内部属性 necessary for 内置 async function behaviour.
25.7.1.1AsyncFunction( p1, p2, … , pn, body )
The last argument specifies the body (executable code) of an async function. Any preceding arguments specify formal parameters.
When the AsyncFunction function is called with some arguments p1, p2, …, pn, body (where n might be 0, that is, there are no p arguments, and where body might also not be provided), 执行如下:
The AsyncFunction 原型对象 is an 普通对象. It is not a 函数对象 and does not have an [[ECMAScriptCode]] 内部属性 or any other of the 内部属性 listed in Table 27. In addition to being the value of the prototype property of the %AsyncFunction% intrinsic, it is the %AsyncFunctionPrototype% intrinsic.
[[Prototype]] 内部属性的值 of the AsyncFunction 原型对象 is the %FunctionPrototype% 内部对象. The 初始值 of the [[Extensible]] 内部属性 of the AsyncFunction 原型对象 is true.
25.7.3.1AsyncFunction.prototype.constructor
The 初始值 of AsyncFunction.prototype.constructor is the 内部对象 %AsyncFunction%
Every AsyncFunction instance is an ES 函数对象 and has the 内部属性 listed in Table 27. The value of the [[FunctionKind]] 内部属性 for all such instances is "async". 异步函数实例 are not constructors and do not have a [[Construct]] 内部方法. 异步函数实例 do not have a prototype property as they are not constructable.
Each AsyncFunction instance 拥有以下自身属性:
25.7.4.1length
The specification for the length property of 函数实例 given in 19.2.4.1 also applies to 异步函数实例.
25.7.4.2name
The specification for the name property of 函数实例 given in 19.2.4.2 also applies to 异步函数实例.
The 抽象操作 AsyncFunctionCreate requires the arguments: kind which is one of (Normal, Method, Arrow), a parameter list 解析节点 specified by parameters, a body 解析节点 specified by body, a 词法环境 specified by Scope, and a Boolean flag Strict. AsyncFunctionCreate 执行如下:
Push asyncContext onto the 执行上下文 堆栈; asyncContext is now the 运行时执行上下文.
Resume the suspended 估值 of asyncContext. Let result be the value returned by the resumed computation.
Assert: When we return here, asyncContext has already been removed from the 执行上下文 堆栈 and runningContext is the currently 运行时执行上下文.
Assert: result is a normal completion with a value of undefined. The possible sources of completion values are Await or, if the async function doesn't await anything, the step 3.g above.
Return.
26映射
26.1Reflect 对象
Reflect 对象 is the %Reflect% 内部对象 and the 初始值 of the Reflect property of the 全局对象. Reflect 对象 is an 普通对象.
Reflect 对象 is not a 函数对象. It does not have a [[Construct]] 内部方法; it is not possible to use Reflect 对象 as a 构造器 with new 运算符. Reflect 对象 also does not have a [[Call]] 内部方法; it is not possible to invoke Reflect 对象 as a function.
If Type(proto) is not Object and proto is not null, 抛出一个 TypeError 异常.
Return ? target.[[SetPrototypeOf]](proto).
26.2Proxy 对象
26.2.1The Proxy 构造器
The Proxy 构造器 is the %Proxy% 内部对象 and the 初始值 of the Proxy property of the 全局对象. When called as a 构造器 它会创建和初始化一个新的 proxy 外来对象. Proxy is not intended to be called as a function and will 抛出一个异常 when called in that manner.
26.2.1.1Proxy ( target, handler )
When Proxy is called with arguments target and handler 执行如下:
The length property of a Proxy revocation function is 0.
26.3模块命名空间对象
A 模块命名空间对象 is a module 命名空间 外来对象 that provides runtime property-based access to a module's exported bindings. There is no 构造器 function for 模块命名空间对象. Instead, such an object is created for each module that is imported by an ImportDeclaration that includes a NameSpaceImport.
In addition to the properties specified in 9.4.6 each 模块命名空间对象 has the following 自身属性:
26.3.1@@toStringTag
The 初始值 of the @@toStringTag property is the String 值 "Module".
The memory consistency model, or 内存模型, specifies the possible orderings of 共享数据块 events, arising via accessing TypedArray instances backed by a SharedArrayBuffer and via methods on Atomics 对象. When the program has no data races (defined below), the ordering of events appears as sequentially consistent, i.e., as an interleaving of actions from each agent. When the program has data races, shared memory operations may appear sequentially inconsistent. 例如, programs may exhibit causality-violating behaviour and other astonishments. These astonishments arise from compiler transforms and the design of CPUs (e.g., out-of-order execution and speculation). The 内存模型 defines both the precise conditions under which a program exhibits sequentially consistent behaviour as well as the possible values read from data races. To wit, there is no undefined behaviour.
The 内存模型 is defined as relational constraints on events introduced by 抽象操作 on SharedArrayBuffer or by methods on Atomics 对象 during an 估值.
Note
This section provides an axiomatic model on events introduced by the 抽象操作 on SharedArrayBuffers. It bears stressing that the model is not expressible algorithmically, unlike the rest of this specification. The nondeterministic 引言 of events by 抽象操作 is the interface between the operational 语义 of ES 估值 and the axiomatic 语义 of the 内存模型. The 语义 of these events is defined by considering graphs of all events in an 估值. These are neither 静态语义 nor 运行时语义. There is no demonstrated 算法实现, but instead a set of constraints that determine if a particular event graph is allowed or disallowed.
27.1内存模型基础
Shared memory accesses (reads and writes) are divided into two groups, atomic accesses and data accesses, defined below. Atomic accesses are sequentially consistent, i.e., there is a strict total ordering of events agreed upon by all 代理 in an agent cluster. Non-atomic accesses do not have a strict total ordering agreed upon by all 代理, i.e., unordered.
Note 1
No orderings weaker than sequentially consistent and stronger than unordered, 例如 release-acquire, are supported.
A 共享数据块 event is either a ReadSharedMemory, WriteSharedMemory, or ReadModifyWriteSharedMemory Record.
The List of byte values to be passed to [[ModifyOp]].
[[ModifyOp]]
A semantic function
A pure semantic function that returns a modified List of byte values from a read List of byte values and [[Payload]].
These events are introduced by 抽象操作 or by methods on Atomics 对象.
In addition to 共享数据块 events, there are host-specific events.
Let the range of a ReadSharedMemory, WriteSharedMemory, or ReadModifyWriteSharedMemory event be the Set of contiguous integers from its [[ByteIndex]] to [[ByteIndex]]+[[ElementSize]]-1. Two events' ranges are equal when the events have the same [[Block]], and the ranges are element-wise equal. Two events' ranges are overlapping when the events have the same [[Block]], the ranges are not equal and their intersection is non-empty. Two events' ranges are disjoint when the events do not have the same [[Block]] or their ranges are neither equal nor overlapping.
Note 2
Examples of host-specific synchronizing events that should be accounted for are: sending a SharedArrayBuffer from one agent to another (e.g., by postMessage in a browser), starting and stopping 代理, and communicating within the agent cluster via channels other than shared memory. It is assumed those events are appended to agent-order during 估值 like the other SharedArrayBuffer events.
共享数据块 events are ordered within candidate executions by the relations defined below.
27.2代理事件记录
An Agent Events Record is a Record with the following fields.
For a candidate executionexecution, execution.[[AgentOrder]] is a Relation on events that satisfies the following.
For each pair (E, D) in EventSet(execution), (E, D) is in execution.[[AgentOrder]] if there is some Agent Events Recordaer in execution.[[EventLists]] such that E and D are in aer.[[EventList]] and E is before D in List order of aer.[[EventList]].
Note
Each agent introduces events in a per-agentstrict total order during the 估值. This is the union of those strict total orders.
Each event W with index i in Ws has R.[[ByteIndex]]+i in its range.
R is not in Ws.
27.6.3reads-from
For a candidate executionexecution, execution.[[ReadsFrom]] is the least Relation on events that satisfies the following.
For each pair (R, W) in SharedDataBlockEventSet(execution), (R, W) is in execution.[[ReadsFrom]] if W is in execution.[[ReadsBytesFrom]](R).
27.6.4host-synchronizes-with
For a candidate executionexecution, execution.[[HostSynchronizesWith]] is a host-provided strict partial order on host-specific events that satisfies at least the following.
If (E, D) is in execution.[[HostSynchronizesWith]], E and D are in HostEventSet(execution).
There is no cycle in the union of execution.[[HostSynchronizesWith]] and execution.[[AgentOrder]].
Note 1
For two host-specific events E and D, E host-synchronizes-with D implies Ehappens-beforeD.
Note 2
The host-synchronizes-with relation allows the host to provide additional synchronization mechanisms, 例如 postMessage between HTML workers.
27.6.5synchronizes-with
For a candidate executionexecution, execution.[[SynchronizesWith]] is the least Relation on events that satisfies the following.
For each pair (R, W) in execution.[[ReadsFrom]], (W, R) is in execution.[[SynchronizesWith]] if all the following are true.
R.[[Order]] is "SeqCst".
W.[[Order]] is "SeqCst" or "Init".
If W.[[Order]] is "SeqCst", then R and W have equal ranges.
If W.[[Order]] is "Init", then for each event V such that (R, V) is in execution.[[ReadsFrom]], V.[[Order]] is "Init".
For each pair (E, D) in execution.[[HostSynchronizesWith]], (E, D) is in execution.[[SynchronizesWith]].
Note 1
Owing to convention, write events synchronizes-with read events, instead of read events synchronizes-with write events.
Note 2
Not all "SeqCst" events related by reads-from are related by synchronizes-with. Only events that also have equal ranges are related by synchronizes-with.
Note 3
For an event R and an event W such that W synchronizes-with R, R may reads-from other writes than W.
27.6.6happens-before
For a candidate executionexecution, execution.[[HappensBefore]] is the least Relation on events that satisfies the following.
For each pair (E, D) in execution.[[AgentOrder]], (E, D) is in execution.[[HappensBefore]].
For each pair (E, D) in execution.[[SynchronizesWith]], (E, D) is in execution.[[HappensBefore]].
For each pair (E, D) in SharedDataBlockEventSet(execution), (E, D) is in execution.[[HappensBefore]] if E.[[Order]] is "Init" and E and D have overlapping ranges.
For each pair (E, D) in EventSet(execution), (E, D) is in execution.[[HappensBefore]] if there is an event F such that the pairs (E, F) and (F, D) are in execution.[[HappensBefore]].
Note
Because happens-before is a superset of agent-order, candidate executions are consistent with the single-thread 估值 语义 of ES.
27.7Properties of Valid Executions
27.7.1Valid Chosen Reads
A candidate executionexecution has valid chosen reads if the following 抽象操作 returns true.
If there is a WriteSharedMemory or ReadModifyWriteSharedMemory event V that has byteLocation in its range such that the pairs (W, V) and (V, R) are in execution.[[HappensBefore]], then
Return false.
Increment byteLocation by 1.
Return true.
27.7.3Tear Free Reads
A candidate executionexecution has tear free reads if the following 抽象操作 returns true.
Assert: The remainder of dividing R.[[ByteIndex]] by R.[[ElementSize]] is 0.
For each event W such that (R, W) is in execution.[[ReadsFrom]] and W.[[NoTear]] is true, do
If R and W have equal ranges, and there is an event V such that V and W have equal ranges, V.[[NoTear]] is true, W is not V, and (R, V) is in execution.[[ReadsFrom]], then
Return false.
Return true.
Note
An event's [[NoTear]] field is true when that event was introduced via accessing an integer TypedArray, and false when introduced via accessing a floating point TypedArray or DataView.
Intuitively, this requirement says when a memory range is accessed in an aligned fashion via an integer TypedArray, a single write event on that range must "win" when in a data race with other write events with equal ranges. More precisely, this requirement says an aligned read event cannot read a value composed of bytes from multiple, different write events all with equal ranges. It is possible, however, for an aligned read event to read from multiple write events with overlapping ranges.
For each pair (E, D) in execution.[[HappensBefore]], (E, D) is in memory-order.
For each pair (E, D) in execution.[[SynchronizesWith]], (E, D) is in memory-order if there is no WriteSharedMemory or ReadModifyWriteSharedMemory event W in SharedDataBlockEventSet(execution) with equal range as D such that W is not E, and the pairs (E, W) and (W, D) are in memory-order.
Note 1
This clause additionally constrains "SeqCst" events on equal ranges.
This clause together with the forward progress guarantee on 代理 ensure the liveness condition that "SeqCst" writes become visible to "SeqCst" reads with equal range in finite time.
A candidate execution has sequentially consistent atomics if a memory-order exists.
Note 3
While memory-order includes all events in EventSet(execution), those that are not constrained by happens-before or synchronizes-with are allowed to occur anywhere in the order.
27.7.5Valid Executions
A candidate executionexecution is a valid execution (or simply an execution) if all of the following are true.
If either (E, D) or (D, E) is in execution.[[ReadsFrom]], then
Return true.
Return false.
27.9Data Races
For an execution execution, two events E and D in SharedDataBlockEventSet(execution) are in a data race if the following 抽象操作 returns true.
If E and D are in a race in execution, then
If E.[[Order]] is not "SeqCst" or D.[[Order]] is not "SeqCst", then
Return true.
If E and D have overlapping ranges, then
Return true.
Return false.
27.10Data Race Freedom
An execution execution is data race free if there are no two events in SharedDataBlockEventSet(execution) that are in a data race.
A program is data race free if all its executions are data race free.
The 内存模型 guarantees sequential consistency of all events for data race free programs.
27.11Shared Memory Guidelines
Note 1
The following are guidelines for ES programmers working with shared memory.
We recommend programs be kept data race free, i.e., make it so that it is impossible for there to be concurrent non-atomic operations on the same memory location. Data race free programs have interleaving 语义 where each step in the 估值 语义 of each agent are interleaved with each other. For data race free programs, it is not necessary to understand the details of the 内存模型. The details are unlikely to build intuition that will help one to better write ES.
More generally, even if a program is not data race free it may have predictable behaviour, so long as atomic operations are not involved in any data races and the operations that race all have the same access size. The simplest way to arrange for atomics not to be involved in races is to ensure that different memory cells are used by atomic and non-atomic operations and that atomic accesses of different sizes are not used to access the same cells at the same time. Effectively, the program should treat shared memory as strongly typed as much as possible. One still cannot depend on the ordering and timing of non-atomic accesses that race, but if memory is treated as strongly typed the racing accesses will not "tear" (bits of their values will not be mixed).
Note 2
The following are guidelines for ES implementers writing compiler transformations for programs using shared memory.
It is desirable to allow most program transformations that are valid in a single-agent setting in a multi-agent setting, to ensure that the performance of each agent in a multi-agent program is as good as it would be in a single-agent setting. Frequently these transformations are hard to judge. We outline some rules about program transformations that are intended to be taken as normative (in that they are implied by the 内存模型 or stronger than what the 内存模型 implies) but which are likely not exhaustive. These rules are intended to apply to program transformations that precede the introductions of the events that make up the agent-order.
Let an agent-order slice be the subset of the agent-order pertaining to a single agent.
Let possible read values of a read event be the set of all values of ValueOfReadEvent for that event across all valid executions.
Any transformation of an agent-order slice that is valid in the absence of shared memory is valid in the presence of shared memory, with the following exceptions.
Atomics are carved in stone: Program transformations must not cause the "SeqCst" events in an agent-order slice to be reordered with its "Unordered" operations, nor its "SeqCst" operations to be reordered with each other, nor may a program transformation remove a "SeqCst" operation from the agent-order.
(In practice, the prohibition on reorderings forces a compiler to assume that every "SeqCst" operation is a synchronization and included in the final memory-order, which it would usually have to assume anyway in the absence of inter-agent program analysis. It also forces the compiler to assume that every call where the callee's effects on the memory-order are unknown may contain "SeqCst" operations.)
Reads must be stable: Any given shared memory read must only observe a single value in an execution.
(例如, if what is semantically a single read in the program is executed multiple times then the program is subsequently allowed to observe only one of the values read. A transformation known as rematerialization can violate this rule.)
Writes must be stable: All observable writes to shared memory must follow from program 语义 in an execution.
(例如, a transformation may not introduce certain observable writes, 例如 by using read-modify-write operations on a larger location to write a smaller datum, writing a value to memory that the program could not have written, or writing a just-read value back to the location it was read from, if that location could have been overwritten by another agent after the read.)
Possible read values must be nonempty: Program transformations cannot cause the possible read values of a shared memory read to become empty.
(Counterintuitively, this rule in effect restricts transformations on writes, because writes have force in 内存模型 insofar as to be read by read events. 例如, writes may be moved and coalesced and sometimes reordered between two "SeqCst" operations, but the transformation may not remove every write that updates a location; some write must be preserved.)
Examples of transformations that remain valid are: merging multiple non-atomic reads from the same location, reordering non-atomic reads, introducing speculative non-atomic reads, merging multiple non-atomic writes to the same location, reordering non-atomic writes to different locations, and hoisting non-atomic reads out of loops even if that affects termination. Note in general that aliased TypedArrays make it hard to prove that locations are different.
Note 3
The following are guidelines for ES implementers generating machine code for shared memory accesses.
For architectures with memory models no weaker than those of ARM or Power, non-atomic stores and loads may be compiled to bare stores and loads on the target architecture. Atomic stores and loads may be compiled down to instructions that guarantee sequential consistency. If no such instructions exist, memory barriers are to be employed, 例如 placing barriers on both sides of a bare store or load. Read-modify-write operations may be compiled to read-modify-write instructions on the target architectrue, 例如 LOCK-prefixed instructions on x86, load-exclusive/store-exclusive instructions on ARM, and load-link/store-conditional instructions on Power.
Specifically, the 内存模型 is intended to allow code generation as follows.
Every atomic operation in the program is assumed to be necessary.
Atomic operations are never rearranged with each other or with non-atomic operations.
Functions are always assumed to perform atomic operations.
Atomic operations are never implemented as read-modify-write operations on larger data, but as non-lock-free atomics if the platform does not have atomic operations of the appropriate size. (We already assume that every platform has normal memory access operations of every interesting size.)
Naive code generation uses these 模式:
Regular loads and stores compile to single load and store instructions.
Lock-free atomic loads and stores compile to a full (sequentially consistent) fence, a regular load or store, and a full fence.
Lock-free atomic read-modify-write accesses compile to a full fence, an atomic read-modify-write instruction sequence, and a full fence.
Non-lock-free atomics compile to a spinlock acquire, a full fence, a series of non-atomic load and store instructions, a full fence, and a spinlock release.
That mapping is correct so long as an atomic operation on an address range does not race with a non-atomic write or with an atomic operation of different size. However, that is all we need: the 内存模型 effectively demotes the atomic operations involved in a race to non-atomic status. On the other hand, the naive mapping is quite strong: it allows atomic operations to be used as sequentially consistent fences, which the 内存模型 does not actually guarantee.
A number of local improvements to those basic 模式 are also intended to be legal:
There are obvious platform-dependent improvements that remove redundant fences. 例如, on x86 the fences around lock-free atomic loads and stores can always be omitted except for the fence following a store, and no fence is needed for lock-free read-modify-write instructions, as these all use LOCK-prefixed instructions. On many platforms there are fences of several strengths, and weaker fences can be used in certain contexts without destroying sequential consistency.
Most modern platforms support lock-free atomics for all the data sizes required by ES atomics. Should non-lock-free atomics be needed, the fences surrounding the body of the atomic operation can usually be folded into the lock and unlock steps. The simplest solution for non-lock-free atomics is to have a single lock word per SharedArrayBuffer.
There are also more complicated platform-dependent local improvements, requiring some code analysis. 例如, two back-to-back fences often have the same effect as a single fence, so if code is generated for two atomic operations in sequence, only a single fence need separate them. On x86, even a single fence separating atomic stores can be omitted, as the fence following a store is only needed to separate the store from a subsequent load.
当 ES 的宿主是 web 浏览器时,定义在本附录中的 ES 语言的语法和语义是被需要的。如果 ES 宿主不是一个 web 浏览器,那么本附录中的内容是规范的但可选的。
Note
本附录描述了各种传统的特征和基于 ES 实现的 web 浏览器的特征。本附录中指定的所有语言特性和行为中都有一个或多个不希望出现的特征,如果没有遗留使用,那么将会从该规范中删除。然而,这些特性被大量的现有网页使用,意味着 web 浏览器必须继续支持它们。本附录中的规范定义了这些遗留特征的互操作实现的要求。
这些功能都不被认为是 ES 语言核心的一部分。当在写新的 ES 代码时,程序员不应使用或假定这些特征和行为的存在。ES 实现不鼓励实现这些功能,除非该实现是 web 浏览器的一部分或是被需要用来运行浏览器所遇到的相同的遗留 ES 代码。
The syntax of 21.2.1 is modified and extended as follows. These changes introduce ambiguities that are broken by the ordering of grammar productions and by contextual information. When parsing using the following grammar, each alternative is considered only if previous production alternatives do not match.
This alternative pattern grammar and 语义 only changes the syntax and 语义 of BMP 模式. The following grammar extensions include productions parameterized with the [U] parameter. However, none of these extensions change the syntax of Unicode 模式 recognized when parsing with the [U] parameter present on the 目标符.
这是一个句法错误如果 IsCharacterClass of the first ClassAtom is true or IsCharacterClass of the second ClassAtom is true and this production has a [U] parameter.
The escape function is a property of the 全局对象. It computes a new version of a String 值 in which certain 代码单元 have been replaced by a hexadecimal escape sequence.
For those 代码单元 being replaced whose value is 0x00FF or less, a two-digit escape sequence of the form %xx is used. For those characters being replaced whose 代码单元 value is greater than 0x00FF, a four-digit escape sequence of the form %uxxxx is used.
The escape function is the %escape% 内部对象. When the escape function is called with one argument string, 执行如下:
The encoding is partly based on the encoding described in RFC 1738, but the entire encoding specified in this standard is described above without regard to the contents of RFC 1738. This encoding does not reflect changes to RFC 1738 made by RFC 3986.
B.2.1.2unescape ( string )
The unescape function is a property of the 全局对象. It computes a new version of a String 值 in which each escape sequence of the sort that might be introduced by the escape function is replaced with the 代码单元 that it represents.
The unescape function is the %unescape% 内部对象. When the unescape function is called with one argument string, 执行如下:
If k ≤ length-6 and the 代码单元 at index k+1 within string is the 代码单元 0x0075 (LATIN SMALL LETTER U) and the four 代码单元 at indices k+2, k+3, k+4, and k+5 within string are all hexadecimal digits, then
Let c be the 代码单元 whose value is the integer represented by the four hexadecimal digits at indices k+2, k+3, k+4, and k+5 within string.
Increase k by 5.
Else if k ≤ length-3 and the two 代码单元 at indices k+1 and k+2 within string are both hexadecimal digits, then
Let c be the 代码单元 whose value is the integer represented by two zeroes plus the two hexadecimal digits at indices k+1 and k+2 within string.
The substr method takes two arguments, start and length, and returns a substring of the result of converting the this object to a String, starting from index start and running for length 代码单元 (or through the end of the String if length is undefined). If start is negative, it is treated as sourceLength+start where sourceLength is the length of the String. 结果是一个 String 值, 而不是一个 String 对象. 执行如下:
Let escapedV be the String 值 that is the same as V except that each occurrence of the 代码单元 0x0022 (QUOTATION MARK) in V has been replaced with the six 代码单元 sequence """.
The property toUTCString is preferred. The toGMTString property is provided principally for compatibility with old code. It is recommended that the toUTCString property be used in new ES 代码.
The 函数对象 that is the 初始值 of Date.prototype.toGMTString is the same 函数对象 that is the 初始值 of Date.prototype.toUTCString.
The compile method completely reinitializes the this object RegExp with a new pattern and flags. An 实现 may interpret use of this method as an assertion that the resulting RegExp 对象 will be used multiple times and hence is a candidate for extra optimization.
Prior to ES 2015, the specification of LabelledStatement did not allow for the association of a statement label with a FunctionDeclaration. However, a labelled FunctionDeclaration was an allowable extension for non-strict code and most browser-hosted ES implementations supported that extension. In ES 2015, the grammar productions for LabelledStatement permits use of FunctionDeclaration as a LabelledItem but 13.13.1 includes an 早期错误 rule that produces a Syntax Error if that occurs. For web browser compatibility, that rule is modified with the addition of the highlighted text:
Prior to ES 2015, the ES specification did not define the occurrence of a FunctionDeclaration as an element of a Block statement's StatementList. However, support for that form of FunctionDeclaration was an allowable extension and most browser-hosted ES implementations permitted them. Unfortunately, the 语义 of such declarations differ among those implementations. Because of these semantic differences, existing web ES 代码 that uses Block level 函数声明 is only portable among browser 实现 if the usage only depends upon the semantic intersection of all of the browser implementations for such declarations. The following are the use cases that fall within that intersection 语义:
A function is declared and only referenced within a single block
One or more FunctionDeclarations whose BindingIdentifier is the name f occur within the function code of an enclosing function g and that declaration is nested within a Block.
No other declaration of f that is not a var declaration occurs within the function code of g
A function is declared and possibly used within a single Block but also referenced by an inner function definition that is not contained within that same Block.
One or more FunctionDeclarations whose BindingIdentifier is the name f occur within the function code of an enclosing function g and that declaration is nested within a Block.
No other declaration of f that is not a var declaration occurs within the function code of g
There is at least one occurrence of f as an IdentifierReference within another function h that is nested within g and no other declaration of f shadows the references to f from within h.
All invocations of h occur after the declaration of f has been evaluated.
A function is declared and possibly used within a single block but also referenced within subsequent blocks.
One or more FunctionDeclaration whose BindingIdentifier is the name f occur within the function code of an enclosing function g and that declaration is nested within a Block.
No other declaration of f that is not a var declaration occurs within the function code of g
There is at least one occurrence of f as an IdentifierReference within the function code of g that lexically follows the Block containing the declaration of f.
The first use case is interoperable with the 语义 of Block level 函数声明 provided by ES 2015. Any pre-existing ES 代码 that employs that use case will operate using the Block level 函数声明 语义 defined by clauses 9, 13, and 14 of this specification.
ES 2015 interoperability for the second and third use cases requires the following extensions to the clause 9, clause 14, clause 18.2.1 and clause 15.1.11 语义.
If an ES 实现 has a mechanism for reporting diagnostic warning messages, a warning should be produced when code contains a FunctionDeclaration for which these compatibility 语义 are applied and introduce observable differences from non-compatibility 语义. 例如, if a var binding is not introduced because its 引言 would create an 早期错误, a warning message should not be produced.
B.3.3.1Changes to FunctionDeclarationInstantiation
NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName, the name of a formal parameter, or another FunctionDeclaration.
If initializedBindings does not contain F and F is not "arguments", then
这是一个句法错误如果 the LexicallyDeclaredNames of StatementList contains any duplicate entries, unless the source code matching this production is not 严格模式代码 and the duplicate entries are only bound by FunctionDeclarations.
B.3.3.5Changes to switch Statement 静态语义: 早期错误
For web browser compatibility, that rule is modified with the addition of the highlighted text:
这是一个句法错误如果 the LexicallyDeclaredNames of CaseBlock contains any duplicate entries, unless the source code matching this production is not 严格模式代码 and the duplicate entries are only bound by FunctionDeclarations.
This production only applies when parsing non-strict code. Code matching this production is processed as if each matching occurrence of FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem of a BlockStatement occupying that position in the source code. The 语义 of such a synthetic BlockStatement includes the web legacy compatibility 语义 specified in B.3.3.
B.3.5VariableStatements in Catch Blocks
The content of subclause 13.15.1 is replaced with the following:
The Block of a Catch clause may contain var declarations that bind a name that is also bound by the CatchParameter. At runtime, such bindings are instantiated in the VariableDeclarationEnvironment. They do not shadow the same-named bindings introduced by the CatchParameter and hence the 初始化器 for such var declarations will assign to the corresponding catch parameter rather than the var binding. The relaxation of the normal 静态语义规则 does not apply to names only bound by for-of statements.
This modified behaviour also applies to var and function declarations introduced by direct eval calls contained within the Block of a Catch clause. This change is accomplished by modifying the 算法 of 18.2.1.3 as follows:
Step 5.d.ii.2.a.i is replaced by:
If thisEnvRec is not the 环境记录 for a Catch clause, 抛出一个 SyntaxError 异常.
An [[IsHTMLDDA]] 内部属性 may exist on 实现-defined objects. Objects with an [[IsHTMLDDA]] 内部属性 behave like undefined in the ToBoolean and 抽象相等比较抽象操作 and when used as an operand for the typeof 运算符.
Note
Objects with an [[IsHTMLDDA]] 内部属性 are never created by this specification. However, the document.all object in web browsers is a host-created 外来对象 with this slot that exists for web compatibility purposes. There are no other known examples of this type of object and implementations should not create any with the 异常 of document.all.
B.3.7.1Changes to ToBoolean
The result column in Table 9 for an 参数类型 of Object is replaced with the following 算法:
implements, interface, let, package, private, protected, public, static, and yield are 保留字 within 严格模式代码. (11.6.2).
A conforming 实现, when processing 严格模式代码, must not extend, as described in B.1.1, the syntax of NumericLiteral to include LegacyOctalIntegerLiteral, nor extend the syntax of DecimalIntegerLiteral to include NonOctalDecimalIntegerLiteral.
A conforming 实现, when processing 严格模式代码, may not extend the syntax of EscapeSequence to include LegacyOctalEscapeSequence as described in B.1.2.
Assignment to an undeclared identifier or otherwise unresolvable reference does not create a property in the 全局对象. When a simple assignment occurs within 严格模式代码, its LeftHandSideExpression must not evaluate to an unresolvable Reference. If it does a ReferenceError 异常 is thrown (6.2.4.9). The LeftHandSideExpression also may not be a reference to a 数据属性 with the 特性 value {[[Writable]]: false}, to an 访问器属性 with the 特性 value {[[Set]]: undefined}, nor to a non-existent property of an object whose [[Extensible]] 内部属性 has the value false. In these cases a TypeError 异常 is thrown (12.15).
Arguments objects for strict functions define a non-configurable 访问器属性"callee" which throws a TypeError 异常 on access (9.4.4.6).
Arguments objects for strict functions do not dynamically share their array-indexed property values with the corresponding formal parameter bindings of their functions. (9.4.4).
For strict functions, if an arguments object is created the binding of the local identifier arguments to the arguments object is immutable and hence may not be the target of an assignment expression. (9.2.13).
严格模式 eval code cannot instantiate variables or functions in the variable environment of the caller to eval. Instead, a new variable environment is created and that environment is used for declaration binding instantiation for the eval code (18.2.1).
If this is evaluated within 严格模式代码, then the this value is not coerced to an object. A this value of undefined or null is not converted to the 全局对象 and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object (9.2.1.2, 19.2.3.1, 19.2.3.3).
When a delete 运算符 occurs within 严格模式代码, a SyntaxError is thrown if its UnaryExpression is a direct reference to a variable, function argument, or function name (12.5.3.1).
When a delete 运算符 occurs within 严格模式代码, a TypeError is thrown if the property to be deleted has the 特性 { [[Configurable]]: false } (12.5.3.2).
An 实现 may not extend, beyond that defined 在本规范中, the meanings within strict functions of properties named caller or arguments of 函数实例.
D在 ES 2015 中可能的兼容性影响的校正和澄清
8.1.1.4.15-8.1.1.4.18 第 5 版和第 5.1 版使用属性存在测试来判定是否已经存在一个与新的全局声明相对应的全局对象属性。而 ES 2015 使用一个自身属性存在测试,这与 web 浏览器最常用的实现相对应。
9.4.2.1: The 5th Edition moved the capture of the current array length prior to the integer conversion of the array index or new length value. However, the captured length value could become invalid if the conversion process has the side-effect of changing the array length. ES 2015 specifies that the current array length must be captured after the possible occurrence of such side-effects.
20.3.1.14: Previous editions permitted the TimeClip 抽象操作 to return either +0 or -0 as the representation of a 0 time value. ES 2015 specifies that +0 always returned. This means that for ES 2015 the time value of a Date object is never observably -0 and methods that return time values never return -0.
20.3.1.15: If a time zone offset is not present, the local time zone is used. Edition 5.1 incorrectly stated that a missing time zone should be interpreted as "z".
20.3.4.36: If the year cannot be represented using the Date Time String Format specified in 20.3.1.15 a RangeError 异常 is thrown. Previous editions did not specify the behaviour for that case.
20.3.4.41: Previous editions did not specify the value returned by Date.prototype.toString when this time value is NaN. ES 2015 specifies the result to be the String 值 is "Invalid Date".
21.2.3.1, 21.2.3.2.4: Any LineTerminator code points in the value of the source property of a RegExp instance must be expressed using an escape sequence. Edition 5.1 only required the escaping of "/".
21.2.5.7, 21.2.5.9: In previous editions, the specifications for String.prototype.match and String.prototype.replace was incorrect for cases where the pattern argument was a RegExp value whose global is flag set. The previous specifications stated that for each attempt to match the pattern, if lastIndex did not change it should be incremented by 1. The correct behaviour is that lastIndex should be incremented by one only if the pattern matched the empty string.
22.1.3.25, 22.1.3.25.1: Previous editions did not specify how a NaN value returned by a comparefn was interpreted by Array.prototype.sort. ES 2015 specifies that 例如 value is treated as if +0 was returned from the comparefn. ES 2015 also specifies that ToNumber is applied to the result returned by a comparefn. In previous editions, the effect of a comparefn result that is not a Number 值 was 实现-dependent. In practice, implementations call ToNumber.
EAdditions and Changes That Introduce Incompatibilities with Prior Editions
11.6: In ES 2015, the valid code points for an IdentifierName are specified in terms of the Unicode properties “ID_Start” and “ID_Continue”. In previous editions, the valid IdentifierName or Identifier code points were specified by enumerating various Unicode 码点 categories.
11.9.1: 在 ES 2015 中,自动分号插入会在一个 do-while 语句的末尾添加一个分号,如果该语句缺少分号。此更改将规范与大多数现有实现的实际行为相一致。
12.2.6.1: 在 ES 2015 中,在对象初始化器中拥有重复的属性名将不会再是一个早期错误。
13.6.7: In ES 2015, the normal completion value of an IfStatement is never the value empty. If no Statement part is evaluated or if the evaluated Statement part produces a normal completion whose value is empty, the completion value of the IfStatement is undefined.
13.7: In ES 2015, if the ( token of a for statement is immediately followed by the token sequence let [ then the let is treated as the start of a LexicalDeclaration. In previous editions such a token sequence would be the start of an Expression.
13.7: In ES 2015, if the ( token of a for-in statement is immediately followed by the token sequence let [ then the let is treated as the start of a ForDeclaration. In previous editions such a token sequence would be the start of an LeftHandSideExpression.
13.7: Prior to ES 2015, an initialization expression could appear as part of the VariableDeclaration that precedes the in keyword. In ES 2015, the ForBinding in that same position does not allow the occurrence of such an 初始化器. In ES 2017, such an 初始化器 is permitted only in non-strict code.
13.11.7: In ES 2015, the normal completion value of a WithStatement is never the value empty. If 估值 of the Statement part of a WithStatement produces a normal completion whose value is empty, the completion value of the WithStatement is undefined.
13.15: In ES 2015, it is an 早期错误 for a Catch clause to contain a var declaration for the same Identifier that appears as the Catch clause parameter. In previous editions, such a variable declaration would be instantiated in the enclosing variable environment but the declaration's 初始化器 value would be assigned to the Catch parameter.
13.15, 18.2.1.3: In ES 2015, a runtime SyntaxError is thrown if a Catch clause evaluates a non-strict direct eval whose eval code includes a var or FunctionDeclaration declaration that binds the same Identifier that appears as the Catch clause parameter.
13.15.8: In ES 2015, the completion value of a TryStatement is never the value empty. If the Block part of a TryStatement evaluates to a normal completion whose value is empty, the completion value of the TryStatement is undefined. If the Block part of a TryStatement evaluates to a throw completion and it has a Catch part that evaluates to a normal completion whose value is empty, the completion value of the TryStatement is undefined if there is no Finally clause or if its Finally clause evalulates to an empty normal completion.
14.3.8 In ES 2015, the 函数对象 that are created as the values of the [[Get]] or [[Set]] 特性 of 访问器属性 in an ObjectLiteral are not 构造器 functions and they do not have a prototype 自身属性. In the previous edition, they were constructors and had a prototype property.
19.1.2.6: In ES 2015, if the argument to Object.freeze is not an object it is treated as if it was a non-extensible 普通对象 with no 自身属性. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.7: In ES 2015, if the argument to Object.getOwnPropertyDescriptor is not an object an attempt is made to coerce the argument using ToObject. If the coercion is successful the result is used in place of the original argument value. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.9: In ES 2015, if the argument to Object.getOwnPropertyNames is not an object an attempt is made to coerce the argument using ToObject. If the coercion is successful the result is used in place of the original argument value. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.11: In ES 2015, if the argument to Object.getPrototypeOf is not an object an attempt is made to coerce the argument using ToObject. If the coercion is successful the result is used in place of the original argument value. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.13: In ES 2015, if the argument to Object.isExtensible is not an object it is treated as if it was a non-extensible 普通对象 with no 自身属性. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.14: In ES 2015, if the argument to Object.isFrozen is not an object it is treated as if it was a non-extensible 普通对象 with no 自身属性. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.15: In ES 2015, if the argument to Object.isSealed is not an object it is treated as if it was a non-extensible 普通对象 with no 自身属性. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.16: In ES 2015, if the argument to Object.keys is not an object an attempt is made to coerce the argument using ToObject. If the coercion is successful the result is used in place of the original argument value. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.17: In ES 2015, if the argument to Object.preventExtensions is not an object it is treated as if it was a non-extensible 普通对象 with no 自身属性. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.1.2.19: In ES 2015, if the argument to Object.seal is not an object it is treated as if it was a non-extensible 普通对象 with no 自身属性. In the previous edition, a non-object argument always causes a TypeError to be thrown.
19.2.3.2: In ES 2015, the [[Prototype]] 内部属性 of a bound function is set to the [[GetPrototypeOf]] value of its target function. In the previous edition, [[Prototype]] was always set to %FunctionPrototype%.
19.2.4.1: In ES 2015, the length property of 函数实例 is configurable. In previous editions it was non-configurable.
19.5.6.2: In ES 2015, the [[Prototype]] 内部属性 of a NativeError构造器 is the Error 构造器. In previous editions it was the Function 原型对象.
20.3.4 In ES 2015, the Date 原型对象 is not a Date instance. In previous editions it was a Date instance whose TimeValue was NaN.
21.1.3.10 In ES 2015, the String.prototype.localeCompare function must treat Strings that are canonically equivalent according to the Unicode standard as being identical. In previous editions implementations were permitted to ignore canonical equivalence and could instead use a bit-wise comparison.
21.1.3.24 and 21.1.3.26 In ES 2015, lowercase/upper conversion processing operates on code points. In previous editions such the conversion processing was only applied to individual 代码单元. The only affected code points are those in the Deseret block of Unicode.
21.1.3.27 In ES 2015, the String.prototype.trim method is defined to recognize 空白 code points that may exists outside of the Unicode BMP. However, as of Unicode 7 no such code points are defined. In previous editions such code points would not have been recognized as 空白.
21.2.3.1 In ES 2015, If the pattern argument is a RegExp instance and the flags argument is not undefined, a new RegExp instance is created just like pattern except that pattern's flags are replaced by the argument flags. In previous editions a TypeError 异常 was thrown when pattern was a RegExp instance and flags was not undefined.
21.2.5 In ES 2015, the RegExp 原型对象 is not a RegExp instance. In previous editions it was a RegExp instance whose pattern is the empty string.
21.2.5 In ES 2015, source, global, ignoreCase, and multiline are 访问器属性 defined on the RegExp 原型对象. In previous editions they were data properties defined on RegExp instances.
FColophon
This specification is authored on GitHub in a plaintext source format called Ecmarkup. Ecmarkup is an HTML and Markdown dialect that provides a framework and toolset for authoring ES specifications in plaintext and processing the specification into a full-featured HTML rendering that follows the editorial conventions for this document. Ecmarkup builds on and integrates a number of other formats and technologies including Grammarkdown for defining syntax and Ecmarkdown for authoring 算法步骤. PDF renderings of this specification are produced by printing the HTML rendering to a PDF.
Prior editions of this specification were authored using Word—the Ecmarkup 源文本 that formed the basis of this edition was produced by converting the ES 2015 Word document to Ecmarkup using an automated conversion tool.
G参考书目
IEEE Std 754-2008: IEEE Standard for Floating-Point Arithmetic. Institute of Electrical and Electronic Engineers, New York (2008)
This document and the information contained herein is provided on an "AS IS" basis and ECMA INTERNATIONAL DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
软件许可
本文档("软件")中包含的所有软件受版权保护,可在 “BSD 许可证” 下被制作成可用的,包括以下。该软件或许会被第三方的权利(权利来自于第三方,而不是 Ecma 国际)约束,包括专利权和第三方权利赋予的无许可证(即使第三方被认为是 Ecma 国际的成员之一)。 SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT http://www.ecma-international.org/memento/codeofconduct.htm FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS.
THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.